Copy array by value












1528















When copying an array in JavaScript to another array:



var arr1 = ['a','b','c'];
var arr2 = arr1;
arr2.push('d'); //Now, arr1 = ['a','b','c','d']


I realized that arr2 refers to the same array as arr1, rather than a new, independent array. How can I copy the array to get two independent arrays?










share|improve this question




















  • 2





    It looks like currently in Chrome 53 and Firefox 48 we have cool performance for slice and splice operations and new spread operator and Array.from have much slower implementation. Look at perfjs.fnfo

    – Pencroff
    Sep 16 '16 at 13:32













  • jsben.ch/#/wQ9RU <= this benchmark gives an overview over the different ways to copy an array

    – EscapeNetscape
    Oct 24 '16 at 18:47











  • jsperf.com/flat-array-copy

    – Walle Cyril
    May 25 '17 at 17:08











  • For this array (one that contains primitive strings) you can use var arr2 = arr1.splice(); to deep copy, but this technique won't work if the elements in your array contain literal structures (i.e. or {}) or prototype objects (i.e. function () {}, new, etc). See my answer below for further solutions.

    – tfmontague
    Aug 27 '17 at 22:37








  • 10





    It's 2017, so you might consider using ES6 features: let arr2 = [...arr1]; developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…

    – Hinrich
    Sep 22 '17 at 8:30
















1528















When copying an array in JavaScript to another array:



var arr1 = ['a','b','c'];
var arr2 = arr1;
arr2.push('d'); //Now, arr1 = ['a','b','c','d']


I realized that arr2 refers to the same array as arr1, rather than a new, independent array. How can I copy the array to get two independent arrays?










share|improve this question




















  • 2





    It looks like currently in Chrome 53 and Firefox 48 we have cool performance for slice and splice operations and new spread operator and Array.from have much slower implementation. Look at perfjs.fnfo

    – Pencroff
    Sep 16 '16 at 13:32













  • jsben.ch/#/wQ9RU <= this benchmark gives an overview over the different ways to copy an array

    – EscapeNetscape
    Oct 24 '16 at 18:47











  • jsperf.com/flat-array-copy

    – Walle Cyril
    May 25 '17 at 17:08











  • For this array (one that contains primitive strings) you can use var arr2 = arr1.splice(); to deep copy, but this technique won't work if the elements in your array contain literal structures (i.e. or {}) or prototype objects (i.e. function () {}, new, etc). See my answer below for further solutions.

    – tfmontague
    Aug 27 '17 at 22:37








  • 10





    It's 2017, so you might consider using ES6 features: let arr2 = [...arr1]; developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…

    – Hinrich
    Sep 22 '17 at 8:30














1528












1528








1528


328






When copying an array in JavaScript to another array:



var arr1 = ['a','b','c'];
var arr2 = arr1;
arr2.push('d'); //Now, arr1 = ['a','b','c','d']


I realized that arr2 refers to the same array as arr1, rather than a new, independent array. How can I copy the array to get two independent arrays?










share|improve this question
















When copying an array in JavaScript to another array:



var arr1 = ['a','b','c'];
var arr2 = arr1;
arr2.push('d'); //Now, arr1 = ['a','b','c','d']


I realized that arr2 refers to the same array as arr1, rather than a new, independent array. How can I copy the array to get two independent arrays?







javascript arrays






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Oct 2 '18 at 21:43









Alexander Abakumov

4,91354773




4,91354773










asked Sep 20 '11 at 13:38









DanDan

7,76941416




7,76941416








  • 2





    It looks like currently in Chrome 53 and Firefox 48 we have cool performance for slice and splice operations and new spread operator and Array.from have much slower implementation. Look at perfjs.fnfo

    – Pencroff
    Sep 16 '16 at 13:32













  • jsben.ch/#/wQ9RU <= this benchmark gives an overview over the different ways to copy an array

    – EscapeNetscape
    Oct 24 '16 at 18:47











  • jsperf.com/flat-array-copy

    – Walle Cyril
    May 25 '17 at 17:08











  • For this array (one that contains primitive strings) you can use var arr2 = arr1.splice(); to deep copy, but this technique won't work if the elements in your array contain literal structures (i.e. or {}) or prototype objects (i.e. function () {}, new, etc). See my answer below for further solutions.

    – tfmontague
    Aug 27 '17 at 22:37








  • 10





    It's 2017, so you might consider using ES6 features: let arr2 = [...arr1]; developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…

    – Hinrich
    Sep 22 '17 at 8:30














  • 2





    It looks like currently in Chrome 53 and Firefox 48 we have cool performance for slice and splice operations and new spread operator and Array.from have much slower implementation. Look at perfjs.fnfo

    – Pencroff
    Sep 16 '16 at 13:32













  • jsben.ch/#/wQ9RU <= this benchmark gives an overview over the different ways to copy an array

    – EscapeNetscape
    Oct 24 '16 at 18:47











  • jsperf.com/flat-array-copy

    – Walle Cyril
    May 25 '17 at 17:08











  • For this array (one that contains primitive strings) you can use var arr2 = arr1.splice(); to deep copy, but this technique won't work if the elements in your array contain literal structures (i.e. or {}) or prototype objects (i.e. function () {}, new, etc). See my answer below for further solutions.

    – tfmontague
    Aug 27 '17 at 22:37








  • 10





    It's 2017, so you might consider using ES6 features: let arr2 = [...arr1]; developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…

    – Hinrich
    Sep 22 '17 at 8:30








2




2





It looks like currently in Chrome 53 and Firefox 48 we have cool performance for slice and splice operations and new spread operator and Array.from have much slower implementation. Look at perfjs.fnfo

– Pencroff
Sep 16 '16 at 13:32







It looks like currently in Chrome 53 and Firefox 48 we have cool performance for slice and splice operations and new spread operator and Array.from have much slower implementation. Look at perfjs.fnfo

– Pencroff
Sep 16 '16 at 13:32















jsben.ch/#/wQ9RU <= this benchmark gives an overview over the different ways to copy an array

– EscapeNetscape
Oct 24 '16 at 18:47





jsben.ch/#/wQ9RU <= this benchmark gives an overview over the different ways to copy an array

– EscapeNetscape
Oct 24 '16 at 18:47













jsperf.com/flat-array-copy

– Walle Cyril
May 25 '17 at 17:08





jsperf.com/flat-array-copy

– Walle Cyril
May 25 '17 at 17:08













For this array (one that contains primitive strings) you can use var arr2 = arr1.splice(); to deep copy, but this technique won't work if the elements in your array contain literal structures (i.e. or {}) or prototype objects (i.e. function () {}, new, etc). See my answer below for further solutions.

– tfmontague
Aug 27 '17 at 22:37







For this array (one that contains primitive strings) you can use var arr2 = arr1.splice(); to deep copy, but this technique won't work if the elements in your array contain literal structures (i.e. or {}) or prototype objects (i.e. function () {}, new, etc). See my answer below for further solutions.

– tfmontague
Aug 27 '17 at 22:37






10




10





It's 2017, so you might consider using ES6 features: let arr2 = [...arr1]; developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…

– Hinrich
Sep 22 '17 at 8:30





It's 2017, so you might consider using ES6 features: let arr2 = [...arr1]; developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…

– Hinrich
Sep 22 '17 at 8:30












33 Answers
33






active

oldest

votes













1 2
next












2441














Use this:



var newArray = oldArray.slice();


Basically, the slice() operation clones the array and returns a reference to a new array. Also note that:



For references, strings and numbers (and not the actual object), slice() copies object references into the new array. Both the original and new array refer to the same object. If a referenced object changes, the changes are visible to both the new and original arrays.



Primitives such as strings and numbers are immutable, so changes to the string or number are impossible.






share|improve this answer





















  • 9





    Regarding performance the following jsPerf tests actually show that var arr2 = arr1.slice() is just as fast as var arr2 = arr1.concat(); JSPerf: jsperf.com/copy-array-slice-vs-concat/5 and jsperf.com/copy-simple-array . The result of jsperf.com/array-copy/5 kind of surprised me to the point I am wondering if the test code is valid.

    – Cohen
    Dec 19 '12 at 18:46








  • 87





    Even though this has already received a ton of upvotes, it deserves another because it properly describes references in JS, which is sort of rare, unfortunately.

    – Wayne Burkett
    Jan 20 '14 at 16:29






  • 31





    @GáborImre you'd add an entire library simply for readability? Really? I'd just add a comment if I were that concerned for readability. See: var newArray = oldArray.slice(); //Clone oldArray to newArray

    – dudewad
    Feb 8 '16 at 19:47








  • 10





    @GáborImre I get that, sure. But answering a specific engineering problem by including an entire library in my opinion is not helpful, it's design bloat. I see developers do that a lot, and then you end up with a project that included an entire framework to replace having to write a single function. Just my M.O., though.

    – dudewad
    Feb 9 '16 at 19:48






  • 2





    Lesson learned: Don't confuse .slice() with .splice(), which gives you an empty array. Big difference.

    – crazypeter
    Feb 28 '18 at 6:20



















441














In Javascript, deep-copy techniques depend on the elements in an array.

Let's start there.



Three types of elements



Elements can be: literal values, literal structures, or prototypes.



// Literal values (type1)
const booleanLiteral = true;
const numberLiteral = 1;
const stringLiteral = 'true';

// Literal structures (type2)
const arrayLiteral = ;
const objectLiteral = {};

// Prototypes (type3)
const booleanPrototype = new Bool(true);
const numberPrototype = new Number(1);
const stringPrototype = new String('true');
const arrayPrototype = new Array();
const objectPrototype = new Object(); # or "new function () {}"


From these elements we can create three types of arrays.



// 1) Array of literal-values (boolean, number, string) 
const type1 = [true, 1, "true"];

// 2) Array of literal-structures (array, object)
const type2 = [, {}];

// 3) Array of prototype-objects (function)
const type3 = [function () {}, function () {}];


Deep copy techniques depend on the three array types



Based on the types of elements in the array, we can use various techniques to deep copy.



Javascript deep copy techniques by element types




  • Array of literal-values (type1)

    The [...myArray], myArray.splice(0), myArray.slice(), and myArray.concat() techniques can be used to deep copy arrays with literal values (boolean, number, and string) only; where the Spread operator [...myArray] has the best performance (https://measurethat.net/Benchmarks/Show/4281/0/spread-array-performance-vs-slice-splice-concat).


  • Array of literal-values (type1) and literal-structures (type2)

    The JSON.parse(JSON.stringify(myArray)) technique can be used to deep copy literal values (boolean, number, string) and literal structures (array, object), but not prototype objects.


  • All arrays (type1, type2, type3)

    The jQuery $.extend(myArray) technique can be used to deep-copy all array-types. Libraries like Underscore and Lo-dash offer similar deep-copy functions to jQuery $.extend(), yet have lower performance. More surprisingly, $.extend() has higher performance than the JSON.parse(JSON.stringify(myArray)) technique http://jsperf.com/js-deep-copy/15.

    And for those developers that shy away from third-party libraries (like jQuery), you can use the following custom function; which has higher performance than $.extend, and deep-copies all arrays.



function copy(aObject) {
if (!aObject) {
return aObject;
}

let v;
let bObject = Array.isArray(aObject) ? : {};
for (const k in aObject) {
v = aObject[k];
bObject[k] = (typeof v === "object") ? copy(v) : v;
}

return bObject;
}


So to answer the question...



Question



var arr1 = ['a','b','c'];
var arr2 = arr1;



I realized that arr2 refers to the same array as arr1, rather than a
new, independent array. How can I copy the array to get two
independent arrays?




Answer



Because arr1 is an array of literal values (boolean, number, or string), you can use any deep copy technique discussed above, where the spread operator ... has the highest performance.



// Highest performance for deep copying literal values
arr2 = [...arr1];

// Any of these techniques will deep copy literal values as well,
// but with lower performance.
arr2 = arr1.slice();
arr2 = arr1.splice(0);
arr2 = arr1.concat();
arr2 = JSON.parse(JSON.stringify(arr1));
arr2 = $.extend(true, , arr1); // jQuery.js needed
arr2 = _.extend(arr1); // Underscore.js needed
arr2 = _.cloneDeep(arr1); // Lo-dash.js needed
arr2 = copy(arr1); // Custom-function needed - as provided above





share|improve this answer





















  • 1





    Many of these approaches do not work well. Using the assignment operator means that you have to reassign the original literal value of arr1. It's very rare that that's going to be the case. Using splice obliterates arr1, so that's not a copy at all. Using JSON will fail if any of the values in the array are Functions or have prototypes (such as a Date).

    – Dancrumb
    Sep 18 '14 at 19:53













  • Using splice is a partial solution. It will fail under far more cases than JSON. Splice creates a deep-copy of strings and numbers, when it moves values - never said it returns a copy.

    – tfmontague
    Oct 3 '14 at 6:50






  • 1





    Why splice(0)? Shouldn't it be slice() ? I think it's supposed not to modify original array, which splice does. @JamesMontagne

    – helpse
    May 14 '15 at 15:29






  • 2





    splice will create pointers to the elements in the original array (shallow copy). splice(0) will allocate new memory (deep copy) for elements in the array which are numbers or strings, and create pointers for all other element types (shallow copy). By passing a start value of zero to the splice function-method, it won't splice any elements from the original array, and therefore it doesn't modify it.

    – tfmontague
    May 21 '15 at 9:35








  • 1





    Actually, there is only one type of array: an array of "somethings". There is no difference between [0,"1",{2:3},function random() {return 4;}, [[5,6,7],[8,9,10],[11,12,13]]] and any other array.

    – wizzwizz4
    Apr 7 '16 at 9:12



















172














You can use array spreads ... to copy arrays.



const itemsCopy = [...items];



Also if want to create a new array with the existing one being part of it:



var parts = ['shoulders', 'knees'];
var lyrics = ['head', ...parts, 'and', 'toes'];


Array spreads are now supported in all major browsers but if you need older support use typescript or babel and compile to ES5.



More info on spreads






share|improve this answer

































    150














    No jQuery needed... Working Example



    var arr2 = arr1.slice()


    This copys the array from the starting position 0 through the end of the array.



    It is important to note that it will work as expected for primitive types (string, number, etc.), and to also explain the expected behavior for reference types...



    If you have an array of Reference types, say of type Object. The array will be copied, but both of the arrays will contain references to the same Object's. So in this case it would seem like the array is copied by reference even though the array is actually copied.






    share|improve this answer





















    • 10





      No this would not be a deep copy.

      – jondavidjohn
      Oct 14 '14 at 22:16











    • Try this; var arr2 = JSON.stringify(arr1); arr2 = JSON.parse(arr2);

      – pradeep1991singh
      Dec 19 '18 at 7:11





















    70














    An alternative to slice is concat, which can be used in 2 ways. The first of these is perhaps more readable as the intended behaviour is very clear:



    var array2 = .concat(array1);


    The second method is:



    var array2 = array1.concat();


    Cohen (in the comments) pointed out that this latter method has better performance.



    The way this works is that the concat method creates a new array consisting of the elements in the object on which it is called followed by the elements of any arrays passed to it as arguments. So when no arguments are passed, it simply copies the array.



    Lee Penkman, also in the comments, points out that if there's a chance array1 is undefined, you can return an empty array as follows:



    var array2 = .concat(array1 || );


    Or, for the second method:



    var array2 = (array1 || ).concat();


    Note that you can also do this with slice: var array2 = (array1 || ).slice();.






    share|improve this answer





















    • 31





      Actually you can also do: var array2 = array1.concat(); It's a lot faster regarding performance. (JSPerf: jsperf.com/copy-simple-array and jsperf.com/copy-array-slice-vs-concat/5

      – Cohen
      Dec 19 '12 at 18:50








    • 4





      Its worth noting that if array1 isn't an array then .concat(array1) returns [array1] e.g. if its undefined you'll get [undefined]. I sometimes do var array2 = .concat(array1 || );

      – lee penkman
      Aug 1 '14 at 8:27





















    50














    This is how I've done it after trying many approaches:



    var newArray = JSON.parse(JSON.stringify(orgArray));


    This will create a new deep copy not related to the first one (not a shallow copy).



    Also this obviously will not clone events and functions, but the good thing you can do it in one line, and it can be used for any kind of object (arrays, strings, numbers, objects ...)






    share|improve this answer





















    • 3





      This is the best one. I use the same method a long time ago and think that there is no more sense in old school recursive loops

      – Vladimir Kharlampidi
      May 5 '14 at 20:28






    • 1





      Be aware that this option doesn't handle well graph-like structures: crashes in presence of cycles, and doesn't preserve shared references.

      – Ruben
      Jun 28 '14 at 23:12






    • 1





      This also fails for things like Date, or indeed, anything that has a prototype. In addition, undefineds get converted to nulls.

      – Dancrumb
      Sep 18 '14 at 19:57








    • 6





      Is no one brave enough to comment on the gross inefficiency in both CPU and memory of serializing to text and then parsing back to an object?

      – Lawrence Dol
      Dec 9 '14 at 23:58






    • 2





      This solution is the only one that worked. Using slice() is really a fake solution.

      – user3888372
      Sep 28 '15 at 11:52



















    18














    Some of mentioned methods work well when working with simple data types like number or string, but when the array contains other objects these methods fail. When we try to pass any object from one array to another it is passed as a reference, not the object.



    Add the following code in your JavaScript file:



    Object.prototype.clone = function() {
    var newObj = (this instanceof Array) ? : {};
    for (i in this) {
    if (i == 'clone')
    continue;
    if (this[i] && typeof this[i] == "object") {
    newObj[i] = this[i].clone();
    }
    else
    newObj[i] = this[i]
    } return newObj;
    };


    And simply use



    var arr1 = ['val_1','val_2','val_3'];
    var arr2 = arr1.clone()


    It will work.






    share|improve this answer





















    • 2





      i get this error when i add this code to my page 'Uncaught RangeError: Maximum call stack size exceeded'

      – sawe
      Jan 21 '13 at 17:56













    • On Which Browser did you see this error??

      – sarvesh singh
      Apr 10 '13 at 12:12






    • 1





      My apologies, this error occurs in chrome if arr1 is not declared. so i copy-pasted the above code, and i get the error, however, if i declare the array arr1, then i do not get the error. You could improve the answer by declaring arr1 just above arr2, i see there are quite a few of 'us' out there who did not recognise that we had to declare arr1 (partly because when i was evaluating your answer, i was in a rush and needed something that 'just works')

      – sawe
      Apr 11 '13 at 5:01











    • .slice() still works fine even if you have objects in your array: jsfiddle.net/edelman/k525g

      – Jason
      May 30 '13 at 19:49






    • 7





      @Jason but the objects are still pointing to the same object so changing one will change the other. jsfiddle.net/k525g/1

      – Samuel
      Jul 8 '13 at 14:39



















    15














    From ES2015,



    var arr2 = [...arr1];





    share|improve this answer































      14














      I personally think Array.from is a more readable solution. By the way, just beware of its browser support.



      //clone
      let x = [1,2,3];
      let y = Array.from(x);

      //deep clone
      let clone = arr => Array.from(arr,item => Array.isArray(item) ? clone(item) : item);
      let x = [1,,[]];
      let y = clone(x);





      share|improve this answer





















      • 1





        Yes, this is very readable. The .slice() solution is completely unintuitive. Thanks for this.

        – Banago
        Jul 27 '16 at 14:46



















      13














      Important!



      Most of answers here works for particular cases.



      If you don't care about deep/nested objects and props use (ES6):



      let clonedArray = [...array]



      but if you want to do deep clone use this instead:



      let cloneArray = JSON.parse(JSON.stringify(array))





      For lodash users:



      let clonedArray = _.clone(array) documentation



      and



      let clonedArray = _.cloneDeep(array) documentation






      share|improve this answer

































        11














        If you are in an environment of ECMAScript 6, using the Spread Operator you could do it this way:






        var arr1 = ['a','b','c'];
        var arr2 = [...arr1]; //copy arr1
        arr2.push('d');

        console.log(arr1)
        console.log(arr2)

        <script src="http://www.wzvang.com/snippet/ignore_this_file.js"></script>








        share|improve this answer

































          9














          Adding to the solution of array.slice(); be aware that if you have multidimensional array sub-arrays will be copied by references.
          What you can do is to loop and slice() each sub-array individually



          var arr = [[1,1,1],[2,2,2],[3,3,3]];
          var arr2 = arr.slice();

          arr2[0][1] = 55;
          console.log(arr2[0][1]);
          console.log(arr[0][1]);

          function arrCpy(arrSrc, arrDis){
          for(elm in arrSrc){
          arrDis.push(arrSrc[elm].slice());
          }
          }

          var arr3=;
          arrCpy(arr,arr3);

          arr3[1][1] = 77;

          console.log(arr3[1][1]);
          console.log(arr[1][1]);


          same things goes to array of objects, they will be copied by reference, you have to copy them manually






          share|improve this answer
























          • This answer deserves a spot near the top of the page! I was working with multidimensional sub arrays and could not follow why the inner arrays were always being copied by ref and not by val. This simple logic solved my problem. I would give you +100 if possible!

            – Mac
            Feb 16 '17 at 1:33



















          6














          As we know in Javascript arrays and objects are by reference, but what ways we can do copy the array without changing the original array later one?



          Here are few ways to do it:



          Imagine we have this array in your code:



          var arr = [1, 2, 3, 4, 5];


          1) Looping through the array in a function and return a new array, like this:



           function newArr(arr) {
          var i=0, res = ;
          while(i<arr.length){
          res.push(arr[i]);
          i++;
          }
          return res;
          }


          2) Using slice method, slice is for slicing part of the array, it will slice some part of your array without touching the original, in the slice, if don't specify the start and end of the array, it will slice the whole array and basically make a full copy of the array, so we can easily say:



          var arr2 = arr.slice(); // make a copy of the original array


          3) Also contact method, this is for merging two array, but we can just specify one of arrays and then this basically make a copy of the values in the new contacted array:



          var arr2 = arr.concat();


          4) Also stringify and parse method, it's not recommended, but can be an easy way to copy Array and Objects:



          var arr2 = JSON.parse(JSON.stringify(arr));


          5) Array.from method, this is not widely supported, before use check the support in different browsers:



          const arr2 = Array.from(arr);


          6) ECMA6 way, also not fully supported, but babelJs can help you if you want to transpile:



          const arr2 = [...arr];





          share|improve this answer

































            4














            In my particular case I needed to ensure the array remained intact so this worked for me:



            // Empty array
            arr1.length = 0;
            // Add items from source array to target array
            for (var i = 0; i < arr2.length; i++) {
            arr1.push(arr2[i]);
            }





            share|improve this answer





















            • 2





              +1 for not adding obscuity to your code by calling a function that does exactly the same thing, but in a less obvious way. slice may be more efficient under the hood, but to anyone working on the code, this shows your intent. plus it makes it easier to optimise later, if you want to (for example) filter what you are copying. note however this does not handle deep copying, and the same internal objects are passed to the new array, by reference. This might be what you want to do, it might not.

              – unsynchronized
              Jun 30 '14 at 22:45



















            4














            Make copy of multidimensional array/object:



            function deepCopy(obj) {
            if (Object.prototype.toString.call(obj) === '[object Array]') {
            var out = , i = 0, len = obj.length;
            for ( ; i < len; i++ ) {
            out[i] = arguments.callee(obj[i]);
            }
            return out;
            }
            if (typeof obj === 'object') {
            var out = {}, i;
            for ( i in obj ) {
            out[i] = arguments.callee(obj[i]);
            }
            return out;
            }
            return obj;
            }


            Thanks to James Padolsey for this function.



            Source: Here






            share|improve this answer





















            • 1





              Nice , helped me. thank you.

              – f.n174
              Jan 2 '15 at 7:57











            • Thank you so much sir

              – Photonic
              Dec 8 '17 at 7:58



















            4














            Dan, no need to use fancy tricks. All you need to do is make copy of arr1 by doing this.






            var arr2 = new Array(arr1);





            Now arr1 and arr2 are two different array variables stored in separate stacks.
            Check this out on jsfiddle.






            share|improve this answer
























            • This doesn't copy the array. It creates an array with one element that references the original (i.e. var arr2 = [arr1];).

              – Timothy003
              Nov 21 '18 at 23:25



















            3














            When we want to copy an array using the assignment operator ( = ) it doesn't create a copy it merely copies the pointer/reference to the array. For example:






            const oldArr = [1,2,3];

            const newArr = oldArr; // now oldArr points to the same place in memory

            console.log(oldArr === newArr); // Points to the same place in memory thus is true

            const copy = [1,2,3];

            console.log(copy === newArr); // Doesn't point to the same place in memory and thus is false





            Often when we transform data we want to keep our initial datastructure (e.g. Array) intact. We do this by making a exact copy of our array so this one can be transformed while the initial one stays intact.



            Ways of copying an array:






            const oldArr = [1,2,3];

            // Uses the spread operator to spread out old values into the new array literal
            const newArr1 = [...oldArr];

            // Slice with no arguments returns the newly copied Array
            const newArr2 = oldArr.slice();

            // Map applies the callback to every element in the array and returns a new array
            const newArr3 = oldArr.map((el) => el);

            // Concat is used to merge arrays and returns a new array. Concat with no args copies an array
            const newArr4 = oldArr.concat();

            // Object.assign can be used to transfer all the properties into a new array literal
            const newArr5 = Object.assign(, oldArr);

            // Creating via the Array constructor using the new keyword
            const newArr6 = new Array(...oldArr);

            // For loop
            function clone(base) {
            const newArray = ;
            for(let i= 0; i < base.length; i++) {
            newArray[i] = base[i];
            }
            return newArray;
            }

            const newArr7 = clone(oldArr);

            console.log(newArr1, newArr2, newArr3, newArr4, newArr5, newArr6, newArr7);





            Be careful when arrays or objects are nested!:



            When arrays are nested the values are copied by reference. Here is an example of how this could lead to issues:






            let arr1 = [1,2,[1,2,3]]

            let arr2 = [...arr1];

            arr2[2][0] = 5; // we change arr2

            console.log(arr1); // arr1 is also changed because the array inside arr1 was copied by reference





            So don't use these methods when there are objects or arrays inside your array you want to copy. i.e. Use these methods on arrays of primitives only.



            If you do want to deepclone a javascript array use JSON.parse in conjunction with JSON.stringify, like this:






            let arr1 = [1,2,[1,2,3]]

            let arr2 = JSON.parse(JSON.stringify(arr1)) ;

            arr2[2][0] = 5;

            console.log(arr1); // now I'm not modified because I'm a deep clone





            Performance of copying:



            So which one do we choose for optimal performance. It turns out that the most verbose method, the for loop has the highest performance. Use the for loop for really CPU intensive copying (large/many arrays).



            After that the .slice() method also has decent performance and is also less verbose and easier for the programmer to implement. I suggest to use .slice() for your everyday copying of arrays which aren't very CPU intensive. Also avoid using the JSON.parse(JSON.stringify(arr)) (lots of overhead) if no deep clone is required and performance is an issue.



            Source performance test






            share|improve this answer

































              2














              If you want to make a new copy of an object or array, you must explicitly copy the properties of the object or the elements of the array, for example:



              var arr1 = ['a','b','c'];
              var arr2 = ;

              for (var i=0; i < arr1.length; i++) {
              arr2[i] = arr1[i];
              }


              You can search for more information on Google about immutable primitive values and mutable object references.






              share|improve this answer





















              • 1





                You don't have to explicitly copy the properties of the objects of the array. See Chtiwi Malek's answer.

                – Magne
                Jun 4 '14 at 14:30





















              2














              Using jQuery deep copy could be made as following:



              var arr2 = $.extend(true, , arr1);





              share|improve this answer































                2














                You can also use ES6 spread operator to copy Array



                var arr=[2,3,4,5];
                var copyArr=[...arr];





                share|improve this answer































                  2














                  Here are few more way to copy:






                  const array = [1,2,3,4];

                  const arrayCopy1 = Object.values(array);
                  const arrayCopy2 = Object.assign(, array);
                  const arrayCopy3 = array.map(i => i);
                  const arrayCopy4 = Array.of(...array );








                  share|improve this answer































                    2














                    Quick Examples:




                    1. If elements in the array are primitive types (string, number, etc.)





                    var arr1 = ['a','b','c'];
                    // arr1 and arr2 are independent and primitive elements are stored in
                    // different places in the memory
                    var arr2 = arr1.slice();
                    arr2.push('d');
                    console.log(arr1); // [ 'a', 'b', 'c' ]
                    console.log(arr2); // [ 'a', 'b', 'c', 'd' ]






                    1. If elements in the array are object literals, another array ({}, )





                    var arr1 = [{ x: 'a', y: 'b'}, [1, 2], [3, 4]];
                    // arr1 and arr2 are independent and reference's/addresses are stored in different
                    // places in the memory. But those reference's/addresses points to some common place
                    // in the memory.
                    var arr2 = arr1.slice();
                    arr2.pop(); // OK - don't affect arr1 bcos only the address in the arr2 is
                    // deleted not the data pointed by that address
                    arr2[0].x = 'z'; // not OK - affect arr1 bcos changes made in the common area
                    // pointed by the addresses in both arr1 and arr2
                    arr2[1][0] = 9; // not OK - same above reason

                    console.log(arr1); // [ { x: 'z', y: 'b' }, [ 9, 2 ], [ 3, 4 ] ]
                    console.log(arr2); // [ { x: 'z', y: 'b' }, [ 9, 2 ] ]







                    1. Solution for 2: Deep Copy by element by element





                    var arr1 = [{ x: 'a', y: 'b'}, [1, 2], [3, 4]];
                    arr2 = JSON.parse(JSON.stringify(arr1));
                    arr2.pop(); // OK - don't affect arr1
                    arr2[0].x = 'z'; // OK - don't affect arr1
                    arr2[1][0] = 9; // OK - don't affect arr1

                    console.log(arr1); // [ { x: 'a', y: 'b' }, [ 1, 2 ], [ 3, 4 ] ]
                    console.log(arr2); // [ { x: 'z', y: 'b' }, [ 9, 2 ] ]








                    share|improve this answer

































                      2














                      If your array contains elements of the primitive data type such as int, char, or string etc then you can user one of those methods which returns a copy of the original array such as .slice() or .map() or spread operator(thanks to ES6).



                      new_array = old_array.slice()


                      or



                      new_array = old_array.map((elem) => elem)


                      or



                      const new_array = new Array(...old_array);


                      BUT if your array contains complex elements such as objects(or arrays) or more nested objects, then, you will have to make sure that you are making a copy of all the elements from the top level to the last level else reference of the inner objects will be used and that means changing values in object_elements in new_array will still affect the old_array. You can call this method of copying at each level as making a DEEP COPY
                      of the old_array.



                      For deep copying, you can use the above-mentioned methods for primitive data types at each level depending upon the type of data or you can use this costly method(mentioned below) for making a deep copy without doing much work.



                      var new_array = JSON.parse(JSON.stringify(old_array));


                      There are a lot of other methods out there which you can use depending on your requirements. I have mentioned only some of those for giving a general idea of what happens when we try to copy an array into the other by value.






                      share|improve this answer































                        1














                        Here's a variant:



                        var arr1=['a', 'b', 'c'];
                        var arr2=eval(arr1.toSource());
                        arr2.push('d');
                        console.log('arr1: '+arr1+'narr2: '+arr2);
                        /*
                        * arr1: a,b,c
                        * arr2: a,b,c,d
                        */





                        share|improve this answer
























                        • not such a bad idea, though I'd better use JSON stringify/parse instead of eval, and yet another jsPerf compare would be good to check out, also note toSource is not standard and will not work in Chrome for example.

                          – dmi3y
                          Mar 24 '14 at 19:23



















                        1














                        There's the newly introduced Array.from, but unfortunately, as of the time of this writing it's only supported on recent Firefox versions (32 and higher). It can be simply used as follows:



                        var arr1 = [1, 2, 3];
                        console.log(Array.from(arr1)); // Logs: [1, 2, 3]


                        Reference: Here



                        Or Array.prototype.map may be used with an identity function:



                        function identity(param)
                        {
                        return param;
                        }

                        var arr1 = [1, 2, 3],
                        clone = arr1.map(identity);


                        Reference: Here






                        share|improve this answer


























                        • +1 for mentioning Array.from, which is now supported on all major browsers except Internet Explorer (source). .

                          – mgthomas99
                          Oct 18 '17 at 11:16





















                        1














                        You can do that in following way :
                        arr2 = arr1.map(x => Object.assign({}, x));






                        share|improve this answer































                          1














                          You could use ES6 with spread Opeartor, its simpler.



                          arr2 = [...arr1];


                          There are limitations..check docs Spread syntax @ mozilla






                          share|improve this answer































                            1














                            Here is how you can do it for array of arrays of primitives of variable depth:



                            // If a is array: 
                            // then call cpArr(a) for each e;
                            // else return a

                            const cpArr = a => Array.isArray(a) && a.map(e => cpArr(e)) || a;

                            let src = [[1,2,3], [4, ["five", "six", 7], true], 8, 9, false];
                            let dst = cpArr(src);


                            https://jsbin.com/xemazog/edit?js,console






                            share|improve this answer

































                              1














                              let a = [1,2,3];


                              Now you can do any one of the following to make a copy of an array.



                              let b = Array.from(a); 


                              OR



                              let b = [...a];


                              OR



                              let b = new Array(...a); 


                              OR



                              let b = a.slice(); 


                              OR



                              let b = a.map(e => e);


                              Now, if i change a,



                              a.push(5); 


                              Then, a is [1,2,3,5] but b is still [1,2,3] as it has different reference.



                              But i think, in all the methods above Array.from is better and made mainly to copy an array.






                              share|improve this answer

































                                0














                                For ES6 array containing objects



                                cloneArray(arr) {
                                return arr.map(x => ({ ...x }));
                                }





                                share|improve this answer



























                                  1 2
                                  next


                                  protected by Tushar Gupta Jul 30 '14 at 12:24



                                  Thank you for your interest in this question.
                                  Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).



                                  Would you like to answer one of these unanswered questions instead?














                                  33 Answers
                                  33






                                  active

                                  oldest

                                  votes








                                  33 Answers
                                  33






                                  active

                                  oldest

                                  votes









                                  active

                                  oldest

                                  votes






                                  active

                                  oldest

                                  votes








                                  1 2
                                  next










                                  2441














                                  Use this:



                                  var newArray = oldArray.slice();


                                  Basically, the slice() operation clones the array and returns a reference to a new array. Also note that:



                                  For references, strings and numbers (and not the actual object), slice() copies object references into the new array. Both the original and new array refer to the same object. If a referenced object changes, the changes are visible to both the new and original arrays.



                                  Primitives such as strings and numbers are immutable, so changes to the string or number are impossible.






                                  share|improve this answer





















                                  • 9





                                    Regarding performance the following jsPerf tests actually show that var arr2 = arr1.slice() is just as fast as var arr2 = arr1.concat(); JSPerf: jsperf.com/copy-array-slice-vs-concat/5 and jsperf.com/copy-simple-array . The result of jsperf.com/array-copy/5 kind of surprised me to the point I am wondering if the test code is valid.

                                    – Cohen
                                    Dec 19 '12 at 18:46








                                  • 87





                                    Even though this has already received a ton of upvotes, it deserves another because it properly describes references in JS, which is sort of rare, unfortunately.

                                    – Wayne Burkett
                                    Jan 20 '14 at 16:29






                                  • 31





                                    @GáborImre you'd add an entire library simply for readability? Really? I'd just add a comment if I were that concerned for readability. See: var newArray = oldArray.slice(); //Clone oldArray to newArray

                                    – dudewad
                                    Feb 8 '16 at 19:47








                                  • 10





                                    @GáborImre I get that, sure. But answering a specific engineering problem by including an entire library in my opinion is not helpful, it's design bloat. I see developers do that a lot, and then you end up with a project that included an entire framework to replace having to write a single function. Just my M.O., though.

                                    – dudewad
                                    Feb 9 '16 at 19:48






                                  • 2





                                    Lesson learned: Don't confuse .slice() with .splice(), which gives you an empty array. Big difference.

                                    – crazypeter
                                    Feb 28 '18 at 6:20
















                                  2441














                                  Use this:



                                  var newArray = oldArray.slice();


                                  Basically, the slice() operation clones the array and returns a reference to a new array. Also note that:



                                  For references, strings and numbers (and not the actual object), slice() copies object references into the new array. Both the original and new array refer to the same object. If a referenced object changes, the changes are visible to both the new and original arrays.



                                  Primitives such as strings and numbers are immutable, so changes to the string or number are impossible.






                                  share|improve this answer





















                                  • 9





                                    Regarding performance the following jsPerf tests actually show that var arr2 = arr1.slice() is just as fast as var arr2 = arr1.concat(); JSPerf: jsperf.com/copy-array-slice-vs-concat/5 and jsperf.com/copy-simple-array . The result of jsperf.com/array-copy/5 kind of surprised me to the point I am wondering if the test code is valid.

                                    – Cohen
                                    Dec 19 '12 at 18:46








                                  • 87





                                    Even though this has already received a ton of upvotes, it deserves another because it properly describes references in JS, which is sort of rare, unfortunately.

                                    – Wayne Burkett
                                    Jan 20 '14 at 16:29






                                  • 31





                                    @GáborImre you'd add an entire library simply for readability? Really? I'd just add a comment if I were that concerned for readability. See: var newArray = oldArray.slice(); //Clone oldArray to newArray

                                    – dudewad
                                    Feb 8 '16 at 19:47








                                  • 10





                                    @GáborImre I get that, sure. But answering a specific engineering problem by including an entire library in my opinion is not helpful, it's design bloat. I see developers do that a lot, and then you end up with a project that included an entire framework to replace having to write a single function. Just my M.O., though.

                                    – dudewad
                                    Feb 9 '16 at 19:48






                                  • 2





                                    Lesson learned: Don't confuse .slice() with .splice(), which gives you an empty array. Big difference.

                                    – crazypeter
                                    Feb 28 '18 at 6:20














                                  2441












                                  2441








                                  2441







                                  Use this:



                                  var newArray = oldArray.slice();


                                  Basically, the slice() operation clones the array and returns a reference to a new array. Also note that:



                                  For references, strings and numbers (and not the actual object), slice() copies object references into the new array. Both the original and new array refer to the same object. If a referenced object changes, the changes are visible to both the new and original arrays.



                                  Primitives such as strings and numbers are immutable, so changes to the string or number are impossible.






                                  share|improve this answer















                                  Use this:



                                  var newArray = oldArray.slice();


                                  Basically, the slice() operation clones the array and returns a reference to a new array. Also note that:



                                  For references, strings and numbers (and not the actual object), slice() copies object references into the new array. Both the original and new array refer to the same object. If a referenced object changes, the changes are visible to both the new and original arrays.



                                  Primitives such as strings and numbers are immutable, so changes to the string or number are impossible.







                                  share|improve this answer














                                  share|improve this answer



                                  share|improve this answer








                                  edited Oct 2 '18 at 21:45









                                  Alexander Abakumov

                                  4,91354773




                                  4,91354773










                                  answered Sep 20 '11 at 13:41









                                  SaketSaket

                                  34.4k94974




                                  34.4k94974








                                  • 9





                                    Regarding performance the following jsPerf tests actually show that var arr2 = arr1.slice() is just as fast as var arr2 = arr1.concat(); JSPerf: jsperf.com/copy-array-slice-vs-concat/5 and jsperf.com/copy-simple-array . The result of jsperf.com/array-copy/5 kind of surprised me to the point I am wondering if the test code is valid.

                                    – Cohen
                                    Dec 19 '12 at 18:46








                                  • 87





                                    Even though this has already received a ton of upvotes, it deserves another because it properly describes references in JS, which is sort of rare, unfortunately.

                                    – Wayne Burkett
                                    Jan 20 '14 at 16:29






                                  • 31





                                    @GáborImre you'd add an entire library simply for readability? Really? I'd just add a comment if I were that concerned for readability. See: var newArray = oldArray.slice(); //Clone oldArray to newArray

                                    – dudewad
                                    Feb 8 '16 at 19:47








                                  • 10





                                    @GáborImre I get that, sure. But answering a specific engineering problem by including an entire library in my opinion is not helpful, it's design bloat. I see developers do that a lot, and then you end up with a project that included an entire framework to replace having to write a single function. Just my M.O., though.

                                    – dudewad
                                    Feb 9 '16 at 19:48






                                  • 2





                                    Lesson learned: Don't confuse .slice() with .splice(), which gives you an empty array. Big difference.

                                    – crazypeter
                                    Feb 28 '18 at 6:20














                                  • 9





                                    Regarding performance the following jsPerf tests actually show that var arr2 = arr1.slice() is just as fast as var arr2 = arr1.concat(); JSPerf: jsperf.com/copy-array-slice-vs-concat/5 and jsperf.com/copy-simple-array . The result of jsperf.com/array-copy/5 kind of surprised me to the point I am wondering if the test code is valid.

                                    – Cohen
                                    Dec 19 '12 at 18:46








                                  • 87





                                    Even though this has already received a ton of upvotes, it deserves another because it properly describes references in JS, which is sort of rare, unfortunately.

                                    – Wayne Burkett
                                    Jan 20 '14 at 16:29






                                  • 31





                                    @GáborImre you'd add an entire library simply for readability? Really? I'd just add a comment if I were that concerned for readability. See: var newArray = oldArray.slice(); //Clone oldArray to newArray

                                    – dudewad
                                    Feb 8 '16 at 19:47








                                  • 10





                                    @GáborImre I get that, sure. But answering a specific engineering problem by including an entire library in my opinion is not helpful, it's design bloat. I see developers do that a lot, and then you end up with a project that included an entire framework to replace having to write a single function. Just my M.O., though.

                                    – dudewad
                                    Feb 9 '16 at 19:48






                                  • 2





                                    Lesson learned: Don't confuse .slice() with .splice(), which gives you an empty array. Big difference.

                                    – crazypeter
                                    Feb 28 '18 at 6:20








                                  9




                                  9





                                  Regarding performance the following jsPerf tests actually show that var arr2 = arr1.slice() is just as fast as var arr2 = arr1.concat(); JSPerf: jsperf.com/copy-array-slice-vs-concat/5 and jsperf.com/copy-simple-array . The result of jsperf.com/array-copy/5 kind of surprised me to the point I am wondering if the test code is valid.

                                  – Cohen
                                  Dec 19 '12 at 18:46







                                  Regarding performance the following jsPerf tests actually show that var arr2 = arr1.slice() is just as fast as var arr2 = arr1.concat(); JSPerf: jsperf.com/copy-array-slice-vs-concat/5 and jsperf.com/copy-simple-array . The result of jsperf.com/array-copy/5 kind of surprised me to the point I am wondering if the test code is valid.

                                  – Cohen
                                  Dec 19 '12 at 18:46






                                  87




                                  87





                                  Even though this has already received a ton of upvotes, it deserves another because it properly describes references in JS, which is sort of rare, unfortunately.

                                  – Wayne Burkett
                                  Jan 20 '14 at 16:29





                                  Even though this has already received a ton of upvotes, it deserves another because it properly describes references in JS, which is sort of rare, unfortunately.

                                  – Wayne Burkett
                                  Jan 20 '14 at 16:29




                                  31




                                  31





                                  @GáborImre you'd add an entire library simply for readability? Really? I'd just add a comment if I were that concerned for readability. See: var newArray = oldArray.slice(); //Clone oldArray to newArray

                                  – dudewad
                                  Feb 8 '16 at 19:47







                                  @GáborImre you'd add an entire library simply for readability? Really? I'd just add a comment if I were that concerned for readability. See: var newArray = oldArray.slice(); //Clone oldArray to newArray

                                  – dudewad
                                  Feb 8 '16 at 19:47






                                  10




                                  10





                                  @GáborImre I get that, sure. But answering a specific engineering problem by including an entire library in my opinion is not helpful, it's design bloat. I see developers do that a lot, and then you end up with a project that included an entire framework to replace having to write a single function. Just my M.O., though.

                                  – dudewad
                                  Feb 9 '16 at 19:48





                                  @GáborImre I get that, sure. But answering a specific engineering problem by including an entire library in my opinion is not helpful, it's design bloat. I see developers do that a lot, and then you end up with a project that included an entire framework to replace having to write a single function. Just my M.O., though.

                                  – dudewad
                                  Feb 9 '16 at 19:48




                                  2




                                  2





                                  Lesson learned: Don't confuse .slice() with .splice(), which gives you an empty array. Big difference.

                                  – crazypeter
                                  Feb 28 '18 at 6:20





                                  Lesson learned: Don't confuse .slice() with .splice(), which gives you an empty array. Big difference.

                                  – crazypeter
                                  Feb 28 '18 at 6:20













                                  441














                                  In Javascript, deep-copy techniques depend on the elements in an array.

                                  Let's start there.



                                  Three types of elements



                                  Elements can be: literal values, literal structures, or prototypes.



                                  // Literal values (type1)
                                  const booleanLiteral = true;
                                  const numberLiteral = 1;
                                  const stringLiteral = 'true';

                                  // Literal structures (type2)
                                  const arrayLiteral = ;
                                  const objectLiteral = {};

                                  // Prototypes (type3)
                                  const booleanPrototype = new Bool(true);
                                  const numberPrototype = new Number(1);
                                  const stringPrototype = new String('true');
                                  const arrayPrototype = new Array();
                                  const objectPrototype = new Object(); # or "new function () {}"


                                  From these elements we can create three types of arrays.



                                  // 1) Array of literal-values (boolean, number, string) 
                                  const type1 = [true, 1, "true"];

                                  // 2) Array of literal-structures (array, object)
                                  const type2 = [, {}];

                                  // 3) Array of prototype-objects (function)
                                  const type3 = [function () {}, function () {}];


                                  Deep copy techniques depend on the three array types



                                  Based on the types of elements in the array, we can use various techniques to deep copy.



                                  Javascript deep copy techniques by element types




                                  • Array of literal-values (type1)

                                    The [...myArray], myArray.splice(0), myArray.slice(), and myArray.concat() techniques can be used to deep copy arrays with literal values (boolean, number, and string) only; where the Spread operator [...myArray] has the best performance (https://measurethat.net/Benchmarks/Show/4281/0/spread-array-performance-vs-slice-splice-concat).


                                  • Array of literal-values (type1) and literal-structures (type2)

                                    The JSON.parse(JSON.stringify(myArray)) technique can be used to deep copy literal values (boolean, number, string) and literal structures (array, object), but not prototype objects.


                                  • All arrays (type1, type2, type3)

                                    The jQuery $.extend(myArray) technique can be used to deep-copy all array-types. Libraries like Underscore and Lo-dash offer similar deep-copy functions to jQuery $.extend(), yet have lower performance. More surprisingly, $.extend() has higher performance than the JSON.parse(JSON.stringify(myArray)) technique http://jsperf.com/js-deep-copy/15.

                                    And for those developers that shy away from third-party libraries (like jQuery), you can use the following custom function; which has higher performance than $.extend, and deep-copies all arrays.



                                  function copy(aObject) {
                                  if (!aObject) {
                                  return aObject;
                                  }

                                  let v;
                                  let bObject = Array.isArray(aObject) ? : {};
                                  for (const k in aObject) {
                                  v = aObject[k];
                                  bObject[k] = (typeof v === "object") ? copy(v) : v;
                                  }

                                  return bObject;
                                  }


                                  So to answer the question...



                                  Question



                                  var arr1 = ['a','b','c'];
                                  var arr2 = arr1;



                                  I realized that arr2 refers to the same array as arr1, rather than a
                                  new, independent array. How can I copy the array to get two
                                  independent arrays?




                                  Answer



                                  Because arr1 is an array of literal values (boolean, number, or string), you can use any deep copy technique discussed above, where the spread operator ... has the highest performance.



                                  // Highest performance for deep copying literal values
                                  arr2 = [...arr1];

                                  // Any of these techniques will deep copy literal values as well,
                                  // but with lower performance.
                                  arr2 = arr1.slice();
                                  arr2 = arr1.splice(0);
                                  arr2 = arr1.concat();
                                  arr2 = JSON.parse(JSON.stringify(arr1));
                                  arr2 = $.extend(true, , arr1); // jQuery.js needed
                                  arr2 = _.extend(arr1); // Underscore.js needed
                                  arr2 = _.cloneDeep(arr1); // Lo-dash.js needed
                                  arr2 = copy(arr1); // Custom-function needed - as provided above





                                  share|improve this answer





















                                  • 1





                                    Many of these approaches do not work well. Using the assignment operator means that you have to reassign the original literal value of arr1. It's very rare that that's going to be the case. Using splice obliterates arr1, so that's not a copy at all. Using JSON will fail if any of the values in the array are Functions or have prototypes (such as a Date).

                                    – Dancrumb
                                    Sep 18 '14 at 19:53













                                  • Using splice is a partial solution. It will fail under far more cases than JSON. Splice creates a deep-copy of strings and numbers, when it moves values - never said it returns a copy.

                                    – tfmontague
                                    Oct 3 '14 at 6:50






                                  • 1





                                    Why splice(0)? Shouldn't it be slice() ? I think it's supposed not to modify original array, which splice does. @JamesMontagne

                                    – helpse
                                    May 14 '15 at 15:29






                                  • 2





                                    splice will create pointers to the elements in the original array (shallow copy). splice(0) will allocate new memory (deep copy) for elements in the array which are numbers or strings, and create pointers for all other element types (shallow copy). By passing a start value of zero to the splice function-method, it won't splice any elements from the original array, and therefore it doesn't modify it.

                                    – tfmontague
                                    May 21 '15 at 9:35








                                  • 1





                                    Actually, there is only one type of array: an array of "somethings". There is no difference between [0,"1",{2:3},function random() {return 4;}, [[5,6,7],[8,9,10],[11,12,13]]] and any other array.

                                    – wizzwizz4
                                    Apr 7 '16 at 9:12
















                                  441














                                  In Javascript, deep-copy techniques depend on the elements in an array.

                                  Let's start there.



                                  Three types of elements



                                  Elements can be: literal values, literal structures, or prototypes.



                                  // Literal values (type1)
                                  const booleanLiteral = true;
                                  const numberLiteral = 1;
                                  const stringLiteral = 'true';

                                  // Literal structures (type2)
                                  const arrayLiteral = ;
                                  const objectLiteral = {};

                                  // Prototypes (type3)
                                  const booleanPrototype = new Bool(true);
                                  const numberPrototype = new Number(1);
                                  const stringPrototype = new String('true');
                                  const arrayPrototype = new Array();
                                  const objectPrototype = new Object(); # or "new function () {}"


                                  From these elements we can create three types of arrays.



                                  // 1) Array of literal-values (boolean, number, string) 
                                  const type1 = [true, 1, "true"];

                                  // 2) Array of literal-structures (array, object)
                                  const type2 = [, {}];

                                  // 3) Array of prototype-objects (function)
                                  const type3 = [function () {}, function () {}];


                                  Deep copy techniques depend on the three array types



                                  Based on the types of elements in the array, we can use various techniques to deep copy.



                                  Javascript deep copy techniques by element types




                                  • Array of literal-values (type1)

                                    The [...myArray], myArray.splice(0), myArray.slice(), and myArray.concat() techniques can be used to deep copy arrays with literal values (boolean, number, and string) only; where the Spread operator [...myArray] has the best performance (https://measurethat.net/Benchmarks/Show/4281/0/spread-array-performance-vs-slice-splice-concat).


                                  • Array of literal-values (type1) and literal-structures (type2)

                                    The JSON.parse(JSON.stringify(myArray)) technique can be used to deep copy literal values (boolean, number, string) and literal structures (array, object), but not prototype objects.


                                  • All arrays (type1, type2, type3)

                                    The jQuery $.extend(myArray) technique can be used to deep-copy all array-types. Libraries like Underscore and Lo-dash offer similar deep-copy functions to jQuery $.extend(), yet have lower performance. More surprisingly, $.extend() has higher performance than the JSON.parse(JSON.stringify(myArray)) technique http://jsperf.com/js-deep-copy/15.

                                    And for those developers that shy away from third-party libraries (like jQuery), you can use the following custom function; which has higher performance than $.extend, and deep-copies all arrays.



                                  function copy(aObject) {
                                  if (!aObject) {
                                  return aObject;
                                  }

                                  let v;
                                  let bObject = Array.isArray(aObject) ? : {};
                                  for (const k in aObject) {
                                  v = aObject[k];
                                  bObject[k] = (typeof v === "object") ? copy(v) : v;
                                  }

                                  return bObject;
                                  }


                                  So to answer the question...



                                  Question



                                  var arr1 = ['a','b','c'];
                                  var arr2 = arr1;



                                  I realized that arr2 refers to the same array as arr1, rather than a
                                  new, independent array. How can I copy the array to get two
                                  independent arrays?




                                  Answer



                                  Because arr1 is an array of literal values (boolean, number, or string), you can use any deep copy technique discussed above, where the spread operator ... has the highest performance.



                                  // Highest performance for deep copying literal values
                                  arr2 = [...arr1];

                                  // Any of these techniques will deep copy literal values as well,
                                  // but with lower performance.
                                  arr2 = arr1.slice();
                                  arr2 = arr1.splice(0);
                                  arr2 = arr1.concat();
                                  arr2 = JSON.parse(JSON.stringify(arr1));
                                  arr2 = $.extend(true, , arr1); // jQuery.js needed
                                  arr2 = _.extend(arr1); // Underscore.js needed
                                  arr2 = _.cloneDeep(arr1); // Lo-dash.js needed
                                  arr2 = copy(arr1); // Custom-function needed - as provided above





                                  share|improve this answer





















                                  • 1





                                    Many of these approaches do not work well. Using the assignment operator means that you have to reassign the original literal value of arr1. It's very rare that that's going to be the case. Using splice obliterates arr1, so that's not a copy at all. Using JSON will fail if any of the values in the array are Functions or have prototypes (such as a Date).

                                    – Dancrumb
                                    Sep 18 '14 at 19:53













                                  • Using splice is a partial solution. It will fail under far more cases than JSON. Splice creates a deep-copy of strings and numbers, when it moves values - never said it returns a copy.

                                    – tfmontague
                                    Oct 3 '14 at 6:50






                                  • 1





                                    Why splice(0)? Shouldn't it be slice() ? I think it's supposed not to modify original array, which splice does. @JamesMontagne

                                    – helpse
                                    May 14 '15 at 15:29






                                  • 2





                                    splice will create pointers to the elements in the original array (shallow copy). splice(0) will allocate new memory (deep copy) for elements in the array which are numbers or strings, and create pointers for all other element types (shallow copy). By passing a start value of zero to the splice function-method, it won't splice any elements from the original array, and therefore it doesn't modify it.

                                    – tfmontague
                                    May 21 '15 at 9:35








                                  • 1





                                    Actually, there is only one type of array: an array of "somethings". There is no difference between [0,"1",{2:3},function random() {return 4;}, [[5,6,7],[8,9,10],[11,12,13]]] and any other array.

                                    – wizzwizz4
                                    Apr 7 '16 at 9:12














                                  441












                                  441








                                  441







                                  In Javascript, deep-copy techniques depend on the elements in an array.

                                  Let's start there.



                                  Three types of elements



                                  Elements can be: literal values, literal structures, or prototypes.



                                  // Literal values (type1)
                                  const booleanLiteral = true;
                                  const numberLiteral = 1;
                                  const stringLiteral = 'true';

                                  // Literal structures (type2)
                                  const arrayLiteral = ;
                                  const objectLiteral = {};

                                  // Prototypes (type3)
                                  const booleanPrototype = new Bool(true);
                                  const numberPrototype = new Number(1);
                                  const stringPrototype = new String('true');
                                  const arrayPrototype = new Array();
                                  const objectPrototype = new Object(); # or "new function () {}"


                                  From these elements we can create three types of arrays.



                                  // 1) Array of literal-values (boolean, number, string) 
                                  const type1 = [true, 1, "true"];

                                  // 2) Array of literal-structures (array, object)
                                  const type2 = [, {}];

                                  // 3) Array of prototype-objects (function)
                                  const type3 = [function () {}, function () {}];


                                  Deep copy techniques depend on the three array types



                                  Based on the types of elements in the array, we can use various techniques to deep copy.



                                  Javascript deep copy techniques by element types




                                  • Array of literal-values (type1)

                                    The [...myArray], myArray.splice(0), myArray.slice(), and myArray.concat() techniques can be used to deep copy arrays with literal values (boolean, number, and string) only; where the Spread operator [...myArray] has the best performance (https://measurethat.net/Benchmarks/Show/4281/0/spread-array-performance-vs-slice-splice-concat).


                                  • Array of literal-values (type1) and literal-structures (type2)

                                    The JSON.parse(JSON.stringify(myArray)) technique can be used to deep copy literal values (boolean, number, string) and literal structures (array, object), but not prototype objects.


                                  • All arrays (type1, type2, type3)

                                    The jQuery $.extend(myArray) technique can be used to deep-copy all array-types. Libraries like Underscore and Lo-dash offer similar deep-copy functions to jQuery $.extend(), yet have lower performance. More surprisingly, $.extend() has higher performance than the JSON.parse(JSON.stringify(myArray)) technique http://jsperf.com/js-deep-copy/15.

                                    And for those developers that shy away from third-party libraries (like jQuery), you can use the following custom function; which has higher performance than $.extend, and deep-copies all arrays.



                                  function copy(aObject) {
                                  if (!aObject) {
                                  return aObject;
                                  }

                                  let v;
                                  let bObject = Array.isArray(aObject) ? : {};
                                  for (const k in aObject) {
                                  v = aObject[k];
                                  bObject[k] = (typeof v === "object") ? copy(v) : v;
                                  }

                                  return bObject;
                                  }


                                  So to answer the question...



                                  Question



                                  var arr1 = ['a','b','c'];
                                  var arr2 = arr1;



                                  I realized that arr2 refers to the same array as arr1, rather than a
                                  new, independent array. How can I copy the array to get two
                                  independent arrays?




                                  Answer



                                  Because arr1 is an array of literal values (boolean, number, or string), you can use any deep copy technique discussed above, where the spread operator ... has the highest performance.



                                  // Highest performance for deep copying literal values
                                  arr2 = [...arr1];

                                  // Any of these techniques will deep copy literal values as well,
                                  // but with lower performance.
                                  arr2 = arr1.slice();
                                  arr2 = arr1.splice(0);
                                  arr2 = arr1.concat();
                                  arr2 = JSON.parse(JSON.stringify(arr1));
                                  arr2 = $.extend(true, , arr1); // jQuery.js needed
                                  arr2 = _.extend(arr1); // Underscore.js needed
                                  arr2 = _.cloneDeep(arr1); // Lo-dash.js needed
                                  arr2 = copy(arr1); // Custom-function needed - as provided above





                                  share|improve this answer















                                  In Javascript, deep-copy techniques depend on the elements in an array.

                                  Let's start there.



                                  Three types of elements



                                  Elements can be: literal values, literal structures, or prototypes.



                                  // Literal values (type1)
                                  const booleanLiteral = true;
                                  const numberLiteral = 1;
                                  const stringLiteral = 'true';

                                  // Literal structures (type2)
                                  const arrayLiteral = ;
                                  const objectLiteral = {};

                                  // Prototypes (type3)
                                  const booleanPrototype = new Bool(true);
                                  const numberPrototype = new Number(1);
                                  const stringPrototype = new String('true');
                                  const arrayPrototype = new Array();
                                  const objectPrototype = new Object(); # or "new function () {}"


                                  From these elements we can create three types of arrays.



                                  // 1) Array of literal-values (boolean, number, string) 
                                  const type1 = [true, 1, "true"];

                                  // 2) Array of literal-structures (array, object)
                                  const type2 = [, {}];

                                  // 3) Array of prototype-objects (function)
                                  const type3 = [function () {}, function () {}];


                                  Deep copy techniques depend on the three array types



                                  Based on the types of elements in the array, we can use various techniques to deep copy.



                                  Javascript deep copy techniques by element types




                                  • Array of literal-values (type1)

                                    The [...myArray], myArray.splice(0), myArray.slice(), and myArray.concat() techniques can be used to deep copy arrays with literal values (boolean, number, and string) only; where the Spread operator [...myArray] has the best performance (https://measurethat.net/Benchmarks/Show/4281/0/spread-array-performance-vs-slice-splice-concat).


                                  • Array of literal-values (type1) and literal-structures (type2)

                                    The JSON.parse(JSON.stringify(myArray)) technique can be used to deep copy literal values (boolean, number, string) and literal structures (array, object), but not prototype objects.


                                  • All arrays (type1, type2, type3)

                                    The jQuery $.extend(myArray) technique can be used to deep-copy all array-types. Libraries like Underscore and Lo-dash offer similar deep-copy functions to jQuery $.extend(), yet have lower performance. More surprisingly, $.extend() has higher performance than the JSON.parse(JSON.stringify(myArray)) technique http://jsperf.com/js-deep-copy/15.

                                    And for those developers that shy away from third-party libraries (like jQuery), you can use the following custom function; which has higher performance than $.extend, and deep-copies all arrays.



                                  function copy(aObject) {
                                  if (!aObject) {
                                  return aObject;
                                  }

                                  let v;
                                  let bObject = Array.isArray(aObject) ? : {};
                                  for (const k in aObject) {
                                  v = aObject[k];
                                  bObject[k] = (typeof v === "object") ? copy(v) : v;
                                  }

                                  return bObject;
                                  }


                                  So to answer the question...



                                  Question



                                  var arr1 = ['a','b','c'];
                                  var arr2 = arr1;



                                  I realized that arr2 refers to the same array as arr1, rather than a
                                  new, independent array. How can I copy the array to get two
                                  independent arrays?




                                  Answer



                                  Because arr1 is an array of literal values (boolean, number, or string), you can use any deep copy technique discussed above, where the spread operator ... has the highest performance.



                                  // Highest performance for deep copying literal values
                                  arr2 = [...arr1];

                                  // Any of these techniques will deep copy literal values as well,
                                  // but with lower performance.
                                  arr2 = arr1.slice();
                                  arr2 = arr1.splice(0);
                                  arr2 = arr1.concat();
                                  arr2 = JSON.parse(JSON.stringify(arr1));
                                  arr2 = $.extend(true, , arr1); // jQuery.js needed
                                  arr2 = _.extend(arr1); // Underscore.js needed
                                  arr2 = _.cloneDeep(arr1); // Lo-dash.js needed
                                  arr2 = copy(arr1); // Custom-function needed - as provided above






                                  share|improve this answer














                                  share|improve this answer



                                  share|improve this answer








                                  edited Nov 25 '18 at 22:45

























                                  answered May 8 '14 at 8:36









                                  tfmontaguetfmontague

                                  7,95113330




                                  7,95113330








                                  • 1





                                    Many of these approaches do not work well. Using the assignment operator means that you have to reassign the original literal value of arr1. It's very rare that that's going to be the case. Using splice obliterates arr1, so that's not a copy at all. Using JSON will fail if any of the values in the array are Functions or have prototypes (such as a Date).

                                    – Dancrumb
                                    Sep 18 '14 at 19:53













                                  • Using splice is a partial solution. It will fail under far more cases than JSON. Splice creates a deep-copy of strings and numbers, when it moves values - never said it returns a copy.

                                    – tfmontague
                                    Oct 3 '14 at 6:50






                                  • 1





                                    Why splice(0)? Shouldn't it be slice() ? I think it's supposed not to modify original array, which splice does. @JamesMontagne

                                    – helpse
                                    May 14 '15 at 15:29






                                  • 2





                                    splice will create pointers to the elements in the original array (shallow copy). splice(0) will allocate new memory (deep copy) for elements in the array which are numbers or strings, and create pointers for all other element types (shallow copy). By passing a start value of zero to the splice function-method, it won't splice any elements from the original array, and therefore it doesn't modify it.

                                    – tfmontague
                                    May 21 '15 at 9:35








                                  • 1





                                    Actually, there is only one type of array: an array of "somethings". There is no difference between [0,"1",{2:3},function random() {return 4;}, [[5,6,7],[8,9,10],[11,12,13]]] and any other array.

                                    – wizzwizz4
                                    Apr 7 '16 at 9:12














                                  • 1





                                    Many of these approaches do not work well. Using the assignment operator means that you have to reassign the original literal value of arr1. It's very rare that that's going to be the case. Using splice obliterates arr1, so that's not a copy at all. Using JSON will fail if any of the values in the array are Functions or have prototypes (such as a Date).

                                    – Dancrumb
                                    Sep 18 '14 at 19:53













                                  • Using splice is a partial solution. It will fail under far more cases than JSON. Splice creates a deep-copy of strings and numbers, when it moves values - never said it returns a copy.

                                    – tfmontague
                                    Oct 3 '14 at 6:50






                                  • 1





                                    Why splice(0)? Shouldn't it be slice() ? I think it's supposed not to modify original array, which splice does. @JamesMontagne

                                    – helpse
                                    May 14 '15 at 15:29






                                  • 2





                                    splice will create pointers to the elements in the original array (shallow copy). splice(0) will allocate new memory (deep copy) for elements in the array which are numbers or strings, and create pointers for all other element types (shallow copy). By passing a start value of zero to the splice function-method, it won't splice any elements from the original array, and therefore it doesn't modify it.

                                    – tfmontague
                                    May 21 '15 at 9:35








                                  • 1





                                    Actually, there is only one type of array: an array of "somethings". There is no difference between [0,"1",{2:3},function random() {return 4;}, [[5,6,7],[8,9,10],[11,12,13]]] and any other array.

                                    – wizzwizz4
                                    Apr 7 '16 at 9:12








                                  1




                                  1





                                  Many of these approaches do not work well. Using the assignment operator means that you have to reassign the original literal value of arr1. It's very rare that that's going to be the case. Using splice obliterates arr1, so that's not a copy at all. Using JSON will fail if any of the values in the array are Functions or have prototypes (such as a Date).

                                  – Dancrumb
                                  Sep 18 '14 at 19:53







                                  Many of these approaches do not work well. Using the assignment operator means that you have to reassign the original literal value of arr1. It's very rare that that's going to be the case. Using splice obliterates arr1, so that's not a copy at all. Using JSON will fail if any of the values in the array are Functions or have prototypes (such as a Date).

                                  – Dancrumb
                                  Sep 18 '14 at 19:53















                                  Using splice is a partial solution. It will fail under far more cases than JSON. Splice creates a deep-copy of strings and numbers, when it moves values - never said it returns a copy.

                                  – tfmontague
                                  Oct 3 '14 at 6:50





                                  Using splice is a partial solution. It will fail under far more cases than JSON. Splice creates a deep-copy of strings and numbers, when it moves values - never said it returns a copy.

                                  – tfmontague
                                  Oct 3 '14 at 6:50




                                  1




                                  1





                                  Why splice(0)? Shouldn't it be slice() ? I think it's supposed not to modify original array, which splice does. @JamesMontagne

                                  – helpse
                                  May 14 '15 at 15:29





                                  Why splice(0)? Shouldn't it be slice() ? I think it's supposed not to modify original array, which splice does. @JamesMontagne

                                  – helpse
                                  May 14 '15 at 15:29




                                  2




                                  2





                                  splice will create pointers to the elements in the original array (shallow copy). splice(0) will allocate new memory (deep copy) for elements in the array which are numbers or strings, and create pointers for all other element types (shallow copy). By passing a start value of zero to the splice function-method, it won't splice any elements from the original array, and therefore it doesn't modify it.

                                  – tfmontague
                                  May 21 '15 at 9:35







                                  splice will create pointers to the elements in the original array (shallow copy). splice(0) will allocate new memory (deep copy) for elements in the array which are numbers or strings, and create pointers for all other element types (shallow copy). By passing a start value of zero to the splice function-method, it won't splice any elements from the original array, and therefore it doesn't modify it.

                                  – tfmontague
                                  May 21 '15 at 9:35






                                  1




                                  1





                                  Actually, there is only one type of array: an array of "somethings". There is no difference between [0,"1",{2:3},function random() {return 4;}, [[5,6,7],[8,9,10],[11,12,13]]] and any other array.

                                  – wizzwizz4
                                  Apr 7 '16 at 9:12





                                  Actually, there is only one type of array: an array of "somethings". There is no difference between [0,"1",{2:3},function random() {return 4;}, [[5,6,7],[8,9,10],[11,12,13]]] and any other array.

                                  – wizzwizz4
                                  Apr 7 '16 at 9:12











                                  172














                                  You can use array spreads ... to copy arrays.



                                  const itemsCopy = [...items];



                                  Also if want to create a new array with the existing one being part of it:



                                  var parts = ['shoulders', 'knees'];
                                  var lyrics = ['head', ...parts, 'and', 'toes'];


                                  Array spreads are now supported in all major browsers but if you need older support use typescript or babel and compile to ES5.



                                  More info on spreads






                                  share|improve this answer






























                                    172














                                    You can use array spreads ... to copy arrays.



                                    const itemsCopy = [...items];



                                    Also if want to create a new array with the existing one being part of it:



                                    var parts = ['shoulders', 'knees'];
                                    var lyrics = ['head', ...parts, 'and', 'toes'];


                                    Array spreads are now supported in all major browsers but if you need older support use typescript or babel and compile to ES5.



                                    More info on spreads






                                    share|improve this answer




























                                      172












                                      172








                                      172







                                      You can use array spreads ... to copy arrays.



                                      const itemsCopy = [...items];



                                      Also if want to create a new array with the existing one being part of it:



                                      var parts = ['shoulders', 'knees'];
                                      var lyrics = ['head', ...parts, 'and', 'toes'];


                                      Array spreads are now supported in all major browsers but if you need older support use typescript or babel and compile to ES5.



                                      More info on spreads






                                      share|improve this answer















                                      You can use array spreads ... to copy arrays.



                                      const itemsCopy = [...items];



                                      Also if want to create a new array with the existing one being part of it:



                                      var parts = ['shoulders', 'knees'];
                                      var lyrics = ['head', ...parts, 'and', 'toes'];


                                      Array spreads are now supported in all major browsers but if you need older support use typescript or babel and compile to ES5.



                                      More info on spreads







                                      share|improve this answer














                                      share|improve this answer



                                      share|improve this answer








                                      edited Jul 5 '17 at 5:57

























                                      answered Jul 3 '15 at 14:46









                                      Luke FemurLuke Femur

                                      1,909188




                                      1,909188























                                          150














                                          No jQuery needed... Working Example



                                          var arr2 = arr1.slice()


                                          This copys the array from the starting position 0 through the end of the array.



                                          It is important to note that it will work as expected for primitive types (string, number, etc.), and to also explain the expected behavior for reference types...



                                          If you have an array of Reference types, say of type Object. The array will be copied, but both of the arrays will contain references to the same Object's. So in this case it would seem like the array is copied by reference even though the array is actually copied.






                                          share|improve this answer





















                                          • 10





                                            No this would not be a deep copy.

                                            – jondavidjohn
                                            Oct 14 '14 at 22:16











                                          • Try this; var arr2 = JSON.stringify(arr1); arr2 = JSON.parse(arr2);

                                            – pradeep1991singh
                                            Dec 19 '18 at 7:11


















                                          150














                                          No jQuery needed... Working Example



                                          var arr2 = arr1.slice()


                                          This copys the array from the starting position 0 through the end of the array.



                                          It is important to note that it will work as expected for primitive types (string, number, etc.), and to also explain the expected behavior for reference types...



                                          If you have an array of Reference types, say of type Object. The array will be copied, but both of the arrays will contain references to the same Object's. So in this case it would seem like the array is copied by reference even though the array is actually copied.






                                          share|improve this answer





















                                          • 10





                                            No this would not be a deep copy.

                                            – jondavidjohn
                                            Oct 14 '14 at 22:16











                                          • Try this; var arr2 = JSON.stringify(arr1); arr2 = JSON.parse(arr2);

                                            – pradeep1991singh
                                            Dec 19 '18 at 7:11
















                                          150












                                          150








                                          150







                                          No jQuery needed... Working Example



                                          var arr2 = arr1.slice()


                                          This copys the array from the starting position 0 through the end of the array.



                                          It is important to note that it will work as expected for primitive types (string, number, etc.), and to also explain the expected behavior for reference types...



                                          If you have an array of Reference types, say of type Object. The array will be copied, but both of the arrays will contain references to the same Object's. So in this case it would seem like the array is copied by reference even though the array is actually copied.






                                          share|improve this answer















                                          No jQuery needed... Working Example



                                          var arr2 = arr1.slice()


                                          This copys the array from the starting position 0 through the end of the array.



                                          It is important to note that it will work as expected for primitive types (string, number, etc.), and to also explain the expected behavior for reference types...



                                          If you have an array of Reference types, say of type Object. The array will be copied, but both of the arrays will contain references to the same Object's. So in this case it would seem like the array is copied by reference even though the array is actually copied.







                                          share|improve this answer














                                          share|improve this answer



                                          share|improve this answer








                                          edited Sep 20 '11 at 14:24

























                                          answered Sep 20 '11 at 13:39









                                          jondavidjohnjondavidjohn

                                          51.2k19101145




                                          51.2k19101145








                                          • 10





                                            No this would not be a deep copy.

                                            – jondavidjohn
                                            Oct 14 '14 at 22:16











                                          • Try this; var arr2 = JSON.stringify(arr1); arr2 = JSON.parse(arr2);

                                            – pradeep1991singh
                                            Dec 19 '18 at 7:11
















                                          • 10





                                            No this would not be a deep copy.

                                            – jondavidjohn
                                            Oct 14 '14 at 22:16











                                          • Try this; var arr2 = JSON.stringify(arr1); arr2 = JSON.parse(arr2);

                                            – pradeep1991singh
                                            Dec 19 '18 at 7:11










                                          10




                                          10





                                          No this would not be a deep copy.

                                          – jondavidjohn
                                          Oct 14 '14 at 22:16





                                          No this would not be a deep copy.

                                          – jondavidjohn
                                          Oct 14 '14 at 22:16













                                          Try this; var arr2 = JSON.stringify(arr1); arr2 = JSON.parse(arr2);

                                          – pradeep1991singh
                                          Dec 19 '18 at 7:11







                                          Try this; var arr2 = JSON.stringify(arr1); arr2 = JSON.parse(arr2);

                                          – pradeep1991singh
                                          Dec 19 '18 at 7:11













                                          70














                                          An alternative to slice is concat, which can be used in 2 ways. The first of these is perhaps more readable as the intended behaviour is very clear:



                                          var array2 = .concat(array1);


                                          The second method is:



                                          var array2 = array1.concat();


                                          Cohen (in the comments) pointed out that this latter method has better performance.



                                          The way this works is that the concat method creates a new array consisting of the elements in the object on which it is called followed by the elements of any arrays passed to it as arguments. So when no arguments are passed, it simply copies the array.



                                          Lee Penkman, also in the comments, points out that if there's a chance array1 is undefined, you can return an empty array as follows:



                                          var array2 = .concat(array1 || );


                                          Or, for the second method:



                                          var array2 = (array1 || ).concat();


                                          Note that you can also do this with slice: var array2 = (array1 || ).slice();.






                                          share|improve this answer





















                                          • 31





                                            Actually you can also do: var array2 = array1.concat(); It's a lot faster regarding performance. (JSPerf: jsperf.com/copy-simple-array and jsperf.com/copy-array-slice-vs-concat/5

                                            – Cohen
                                            Dec 19 '12 at 18:50








                                          • 4





                                            Its worth noting that if array1 isn't an array then .concat(array1) returns [array1] e.g. if its undefined you'll get [undefined]. I sometimes do var array2 = .concat(array1 || );

                                            – lee penkman
                                            Aug 1 '14 at 8:27


















                                          70














                                          An alternative to slice is concat, which can be used in 2 ways. The first of these is perhaps more readable as the intended behaviour is very clear:



                                          var array2 = .concat(array1);


                                          The second method is:



                                          var array2 = array1.concat();


                                          Cohen (in the comments) pointed out that this latter method has better performance.



                                          The way this works is that the concat method creates a new array consisting of the elements in the object on which it is called followed by the elements of any arrays passed to it as arguments. So when no arguments are passed, it simply copies the array.



                                          Lee Penkman, also in the comments, points out that if there's a chance array1 is undefined, you can return an empty array as follows:



                                          var array2 = .concat(array1 || );


                                          Or, for the second method:



                                          var array2 = (array1 || ).concat();


                                          Note that you can also do this with slice: var array2 = (array1 || ).slice();.






                                          share|improve this answer





















                                          • 31





                                            Actually you can also do: var array2 = array1.concat(); It's a lot faster regarding performance. (JSPerf: jsperf.com/copy-simple-array and jsperf.com/copy-array-slice-vs-concat/5

                                            – Cohen
                                            Dec 19 '12 at 18:50








                                          • 4





                                            Its worth noting that if array1 isn't an array then .concat(array1) returns [array1] e.g. if its undefined you'll get [undefined]. I sometimes do var array2 = .concat(array1 || );

                                            – lee penkman
                                            Aug 1 '14 at 8:27
















                                          70












                                          70








                                          70







                                          An alternative to slice is concat, which can be used in 2 ways. The first of these is perhaps more readable as the intended behaviour is very clear:



                                          var array2 = .concat(array1);


                                          The second method is:



                                          var array2 = array1.concat();


                                          Cohen (in the comments) pointed out that this latter method has better performance.



                                          The way this works is that the concat method creates a new array consisting of the elements in the object on which it is called followed by the elements of any arrays passed to it as arguments. So when no arguments are passed, it simply copies the array.



                                          Lee Penkman, also in the comments, points out that if there's a chance array1 is undefined, you can return an empty array as follows:



                                          var array2 = .concat(array1 || );


                                          Or, for the second method:



                                          var array2 = (array1 || ).concat();


                                          Note that you can also do this with slice: var array2 = (array1 || ).slice();.






                                          share|improve this answer















                                          An alternative to slice is concat, which can be used in 2 ways. The first of these is perhaps more readable as the intended behaviour is very clear:



                                          var array2 = .concat(array1);


                                          The second method is:



                                          var array2 = array1.concat();


                                          Cohen (in the comments) pointed out that this latter method has better performance.



                                          The way this works is that the concat method creates a new array consisting of the elements in the object on which it is called followed by the elements of any arrays passed to it as arguments. So when no arguments are passed, it simply copies the array.



                                          Lee Penkman, also in the comments, points out that if there's a chance array1 is undefined, you can return an empty array as follows:



                                          var array2 = .concat(array1 || );


                                          Or, for the second method:



                                          var array2 = (array1 || ).concat();


                                          Note that you can also do this with slice: var array2 = (array1 || ).slice();.







                                          share|improve this answer














                                          share|improve this answer



                                          share|improve this answer








                                          edited May 11 '15 at 19:13

























                                          answered Oct 18 '12 at 0:11









                                          NinjakannonNinjakannon

                                          2,72343052




                                          2,72343052








                                          • 31





                                            Actually you can also do: var array2 = array1.concat(); It's a lot faster regarding performance. (JSPerf: jsperf.com/copy-simple-array and jsperf.com/copy-array-slice-vs-concat/5

                                            – Cohen
                                            Dec 19 '12 at 18:50








                                          • 4





                                            Its worth noting that if array1 isn't an array then .concat(array1) returns [array1] e.g. if its undefined you'll get [undefined]. I sometimes do var array2 = .concat(array1 || );

                                            – lee penkman
                                            Aug 1 '14 at 8:27
















                                          • 31





                                            Actually you can also do: var array2 = array1.concat(); It's a lot faster regarding performance. (JSPerf: jsperf.com/copy-simple-array and jsperf.com/copy-array-slice-vs-concat/5

                                            – Cohen
                                            Dec 19 '12 at 18:50








                                          • 4





                                            Its worth noting that if array1 isn't an array then .concat(array1) returns [array1] e.g. if its undefined you'll get [undefined]. I sometimes do var array2 = .concat(array1 || );

                                            – lee penkman
                                            Aug 1 '14 at 8:27










                                          31




                                          31





                                          Actually you can also do: var array2 = array1.concat(); It's a lot faster regarding performance. (JSPerf: jsperf.com/copy-simple-array and jsperf.com/copy-array-slice-vs-concat/5

                                          – Cohen
                                          Dec 19 '12 at 18:50







                                          Actually you can also do: var array2 = array1.concat(); It's a lot faster regarding performance. (JSPerf: jsperf.com/copy-simple-array and jsperf.com/copy-array-slice-vs-concat/5

                                          – Cohen
                                          Dec 19 '12 at 18:50






                                          4




                                          4





                                          Its worth noting that if array1 isn't an array then .concat(array1) returns [array1] e.g. if its undefined you'll get [undefined]. I sometimes do var array2 = .concat(array1 || );

                                          – lee penkman
                                          Aug 1 '14 at 8:27







                                          Its worth noting that if array1 isn't an array then .concat(array1) returns [array1] e.g. if its undefined you'll get [undefined]. I sometimes do var array2 = .concat(array1 || );

                                          – lee penkman
                                          Aug 1 '14 at 8:27













                                          50














                                          This is how I've done it after trying many approaches:



                                          var newArray = JSON.parse(JSON.stringify(orgArray));


                                          This will create a new deep copy not related to the first one (not a shallow copy).



                                          Also this obviously will not clone events and functions, but the good thing you can do it in one line, and it can be used for any kind of object (arrays, strings, numbers, objects ...)






                                          share|improve this answer





















                                          • 3





                                            This is the best one. I use the same method a long time ago and think that there is no more sense in old school recursive loops

                                            – Vladimir Kharlampidi
                                            May 5 '14 at 20:28






                                          • 1





                                            Be aware that this option doesn't handle well graph-like structures: crashes in presence of cycles, and doesn't preserve shared references.

                                            – Ruben
                                            Jun 28 '14 at 23:12






                                          • 1





                                            This also fails for things like Date, or indeed, anything that has a prototype. In addition, undefineds get converted to nulls.

                                            – Dancrumb
                                            Sep 18 '14 at 19:57








                                          • 6





                                            Is no one brave enough to comment on the gross inefficiency in both CPU and memory of serializing to text and then parsing back to an object?

                                            – Lawrence Dol
                                            Dec 9 '14 at 23:58






                                          • 2





                                            This solution is the only one that worked. Using slice() is really a fake solution.

                                            – user3888372
                                            Sep 28 '15 at 11:52
















                                          50














                                          This is how I've done it after trying many approaches:



                                          var newArray = JSON.parse(JSON.stringify(orgArray));


                                          This will create a new deep copy not related to the first one (not a shallow copy).



                                          Also this obviously will not clone events and functions, but the good thing you can do it in one line, and it can be used for any kind of object (arrays, strings, numbers, objects ...)






                                          share|improve this answer





















                                          • 3





                                            This is the best one. I use the same method a long time ago and think that there is no more sense in old school recursive loops

                                            – Vladimir Kharlampidi
                                            May 5 '14 at 20:28






                                          • 1





                                            Be aware that this option doesn't handle well graph-like structures: crashes in presence of cycles, and doesn't preserve shared references.

                                            – Ruben
                                            Jun 28 '14 at 23:12






                                          • 1





                                            This also fails for things like Date, or indeed, anything that has a prototype. In addition, undefineds get converted to nulls.

                                            – Dancrumb
                                            Sep 18 '14 at 19:57








                                          • 6





                                            Is no one brave enough to comment on the gross inefficiency in both CPU and memory of serializing to text and then parsing back to an object?

                                            – Lawrence Dol
                                            Dec 9 '14 at 23:58






                                          • 2





                                            This solution is the only one that worked. Using slice() is really a fake solution.

                                            – user3888372
                                            Sep 28 '15 at 11:52














                                          50












                                          50








                                          50







                                          This is how I've done it after trying many approaches:



                                          var newArray = JSON.parse(JSON.stringify(orgArray));


                                          This will create a new deep copy not related to the first one (not a shallow copy).



                                          Also this obviously will not clone events and functions, but the good thing you can do it in one line, and it can be used for any kind of object (arrays, strings, numbers, objects ...)






                                          share|improve this answer















                                          This is how I've done it after trying many approaches:



                                          var newArray = JSON.parse(JSON.stringify(orgArray));


                                          This will create a new deep copy not related to the first one (not a shallow copy).



                                          Also this obviously will not clone events and functions, but the good thing you can do it in one line, and it can be used for any kind of object (arrays, strings, numbers, objects ...)







                                          share|improve this answer














                                          share|improve this answer



                                          share|improve this answer








                                          edited Sep 6 '15 at 11:40









                                          Peter Mortensen

                                          13.8k1987113




                                          13.8k1987113










                                          answered Apr 23 '14 at 13:32









                                          Chtiwi MalekChtiwi Malek

                                          6,92314953




                                          6,92314953








                                          • 3





                                            This is the best one. I use the same method a long time ago and think that there is no more sense in old school recursive loops

                                            – Vladimir Kharlampidi
                                            May 5 '14 at 20:28






                                          • 1





                                            Be aware that this option doesn't handle well graph-like structures: crashes in presence of cycles, and doesn't preserve shared references.

                                            – Ruben
                                            Jun 28 '14 at 23:12






                                          • 1





                                            This also fails for things like Date, or indeed, anything that has a prototype. In addition, undefineds get converted to nulls.

                                            – Dancrumb
                                            Sep 18 '14 at 19:57








                                          • 6





                                            Is no one brave enough to comment on the gross inefficiency in both CPU and memory of serializing to text and then parsing back to an object?

                                            – Lawrence Dol
                                            Dec 9 '14 at 23:58






                                          • 2





                                            This solution is the only one that worked. Using slice() is really a fake solution.

                                            – user3888372
                                            Sep 28 '15 at 11:52














                                          • 3





                                            This is the best one. I use the same method a long time ago and think that there is no more sense in old school recursive loops

                                            – Vladimir Kharlampidi
                                            May 5 '14 at 20:28






                                          • 1





                                            Be aware that this option doesn't handle well graph-like structures: crashes in presence of cycles, and doesn't preserve shared references.

                                            – Ruben
                                            Jun 28 '14 at 23:12






                                          • 1





                                            This also fails for things like Date, or indeed, anything that has a prototype. In addition, undefineds get converted to nulls.

                                            – Dancrumb
                                            Sep 18 '14 at 19:57








                                          • 6





                                            Is no one brave enough to comment on the gross inefficiency in both CPU and memory of serializing to text and then parsing back to an object?

                                            – Lawrence Dol
                                            Dec 9 '14 at 23:58






                                          • 2





                                            This solution is the only one that worked. Using slice() is really a fake solution.

                                            – user3888372
                                            Sep 28 '15 at 11:52








                                          3




                                          3





                                          This is the best one. I use the same method a long time ago and think that there is no more sense in old school recursive loops

                                          – Vladimir Kharlampidi
                                          May 5 '14 at 20:28





                                          This is the best one. I use the same method a long time ago and think that there is no more sense in old school recursive loops

                                          – Vladimir Kharlampidi
                                          May 5 '14 at 20:28




                                          1




                                          1





                                          Be aware that this option doesn't handle well graph-like structures: crashes in presence of cycles, and doesn't preserve shared references.

                                          – Ruben
                                          Jun 28 '14 at 23:12





                                          Be aware that this option doesn't handle well graph-like structures: crashes in presence of cycles, and doesn't preserve shared references.

                                          – Ruben
                                          Jun 28 '14 at 23:12




                                          1




                                          1





                                          This also fails for things like Date, or indeed, anything that has a prototype. In addition, undefineds get converted to nulls.

                                          – Dancrumb
                                          Sep 18 '14 at 19:57







                                          This also fails for things like Date, or indeed, anything that has a prototype. In addition, undefineds get converted to nulls.

                                          – Dancrumb
                                          Sep 18 '14 at 19:57






                                          6




                                          6





                                          Is no one brave enough to comment on the gross inefficiency in both CPU and memory of serializing to text and then parsing back to an object?

                                          – Lawrence Dol
                                          Dec 9 '14 at 23:58





                                          Is no one brave enough to comment on the gross inefficiency in both CPU and memory of serializing to text and then parsing back to an object?

                                          – Lawrence Dol
                                          Dec 9 '14 at 23:58




                                          2




                                          2





                                          This solution is the only one that worked. Using slice() is really a fake solution.

                                          – user3888372
                                          Sep 28 '15 at 11:52





                                          This solution is the only one that worked. Using slice() is really a fake solution.

                                          – user3888372
                                          Sep 28 '15 at 11:52











                                          18














                                          Some of mentioned methods work well when working with simple data types like number or string, but when the array contains other objects these methods fail. When we try to pass any object from one array to another it is passed as a reference, not the object.



                                          Add the following code in your JavaScript file:



                                          Object.prototype.clone = function() {
                                          var newObj = (this instanceof Array) ? : {};
                                          for (i in this) {
                                          if (i == 'clone')
                                          continue;
                                          if (this[i] && typeof this[i] == "object") {
                                          newObj[i] = this[i].clone();
                                          }
                                          else
                                          newObj[i] = this[i]
                                          } return newObj;
                                          };


                                          And simply use



                                          var arr1 = ['val_1','val_2','val_3'];
                                          var arr2 = arr1.clone()


                                          It will work.






                                          share|improve this answer





















                                          • 2





                                            i get this error when i add this code to my page 'Uncaught RangeError: Maximum call stack size exceeded'

                                            – sawe
                                            Jan 21 '13 at 17:56













                                          • On Which Browser did you see this error??

                                            – sarvesh singh
                                            Apr 10 '13 at 12:12






                                          • 1





                                            My apologies, this error occurs in chrome if arr1 is not declared. so i copy-pasted the above code, and i get the error, however, if i declare the array arr1, then i do not get the error. You could improve the answer by declaring arr1 just above arr2, i see there are quite a few of 'us' out there who did not recognise that we had to declare arr1 (partly because when i was evaluating your answer, i was in a rush and needed something that 'just works')

                                            – sawe
                                            Apr 11 '13 at 5:01











                                          • .slice() still works fine even if you have objects in your array: jsfiddle.net/edelman/k525g

                                            – Jason
                                            May 30 '13 at 19:49






                                          • 7





                                            @Jason but the objects are still pointing to the same object so changing one will change the other. jsfiddle.net/k525g/1

                                            – Samuel
                                            Jul 8 '13 at 14:39
















                                          18














                                          Some of mentioned methods work well when working with simple data types like number or string, but when the array contains other objects these methods fail. When we try to pass any object from one array to another it is passed as a reference, not the object.



                                          Add the following code in your JavaScript file:



                                          Object.prototype.clone = function() {
                                          var newObj = (this instanceof Array) ? : {};
                                          for (i in this) {
                                          if (i == 'clone')
                                          continue;
                                          if (this[i] && typeof this[i] == "object") {
                                          newObj[i] = this[i].clone();
                                          }
                                          else
                                          newObj[i] = this[i]
                                          } return newObj;
                                          };


                                          And simply use



                                          var arr1 = ['val_1','val_2','val_3'];
                                          var arr2 = arr1.clone()


                                          It will work.






                                          share|improve this answer





















                                          • 2





                                            i get this error when i add this code to my page 'Uncaught RangeError: Maximum call stack size exceeded'

                                            – sawe
                                            Jan 21 '13 at 17:56













                                          • On Which Browser did you see this error??

                                            – sarvesh singh
                                            Apr 10 '13 at 12:12






                                          • 1





                                            My apologies, this error occurs in chrome if arr1 is not declared. so i copy-pasted the above code, and i get the error, however, if i declare the array arr1, then i do not get the error. You could improve the answer by declaring arr1 just above arr2, i see there are quite a few of 'us' out there who did not recognise that we had to declare arr1 (partly because when i was evaluating your answer, i was in a rush and needed something that 'just works')

                                            – sawe
                                            Apr 11 '13 at 5:01











                                          • .slice() still works fine even if you have objects in your array: jsfiddle.net/edelman/k525g

                                            – Jason
                                            May 30 '13 at 19:49






                                          • 7





                                            @Jason but the objects are still pointing to the same object so changing one will change the other. jsfiddle.net/k525g/1

                                            – Samuel
                                            Jul 8 '13 at 14:39














                                          18












                                          18








                                          18







                                          Some of mentioned methods work well when working with simple data types like number or string, but when the array contains other objects these methods fail. When we try to pass any object from one array to another it is passed as a reference, not the object.



                                          Add the following code in your JavaScript file:



                                          Object.prototype.clone = function() {
                                          var newObj = (this instanceof Array) ? : {};
                                          for (i in this) {
                                          if (i == 'clone')
                                          continue;
                                          if (this[i] && typeof this[i] == "object") {
                                          newObj[i] = this[i].clone();
                                          }
                                          else
                                          newObj[i] = this[i]
                                          } return newObj;
                                          };


                                          And simply use



                                          var arr1 = ['val_1','val_2','val_3'];
                                          var arr2 = arr1.clone()


                                          It will work.






                                          share|improve this answer















                                          Some of mentioned methods work well when working with simple data types like number or string, but when the array contains other objects these methods fail. When we try to pass any object from one array to another it is passed as a reference, not the object.



                                          Add the following code in your JavaScript file:



                                          Object.prototype.clone = function() {
                                          var newObj = (this instanceof Array) ? : {};
                                          for (i in this) {
                                          if (i == 'clone')
                                          continue;
                                          if (this[i] && typeof this[i] == "object") {
                                          newObj[i] = this[i].clone();
                                          }
                                          else
                                          newObj[i] = this[i]
                                          } return newObj;
                                          };


                                          And simply use



                                          var arr1 = ['val_1','val_2','val_3'];
                                          var arr2 = arr1.clone()


                                          It will work.







                                          share|improve this answer














                                          share|improve this answer



                                          share|improve this answer








                                          edited Sep 6 '15 at 11:39









                                          Peter Mortensen

                                          13.8k1987113




                                          13.8k1987113










                                          answered Dec 12 '12 at 16:22









                                          sarvesh singhsarvesh singh

                                          28934




                                          28934








                                          • 2





                                            i get this error when i add this code to my page 'Uncaught RangeError: Maximum call stack size exceeded'

                                            – sawe
                                            Jan 21 '13 at 17:56













                                          • On Which Browser did you see this error??

                                            – sarvesh singh
                                            Apr 10 '13 at 12:12






                                          • 1





                                            My apologies, this error occurs in chrome if arr1 is not declared. so i copy-pasted the above code, and i get the error, however, if i declare the array arr1, then i do not get the error. You could improve the answer by declaring arr1 just above arr2, i see there are quite a few of 'us' out there who did not recognise that we had to declare arr1 (partly because when i was evaluating your answer, i was in a rush and needed something that 'just works')

                                            – sawe
                                            Apr 11 '13 at 5:01











                                          • .slice() still works fine even if you have objects in your array: jsfiddle.net/edelman/k525g

                                            – Jason
                                            May 30 '13 at 19:49






                                          • 7





                                            @Jason but the objects are still pointing to the same object so changing one will change the other. jsfiddle.net/k525g/1

                                            – Samuel
                                            Jul 8 '13 at 14:39














                                          • 2





                                            i get this error when i add this code to my page 'Uncaught RangeError: Maximum call stack size exceeded'

                                            – sawe
                                            Jan 21 '13 at 17:56













                                          • On Which Browser did you see this error??

                                            – sarvesh singh
                                            Apr 10 '13 at 12:12






                                          • 1





                                            My apologies, this error occurs in chrome if arr1 is not declared. so i copy-pasted the above code, and i get the error, however, if i declare the array arr1, then i do not get the error. You could improve the answer by declaring arr1 just above arr2, i see there are quite a few of 'us' out there who did not recognise that we had to declare arr1 (partly because when i was evaluating your answer, i was in a rush and needed something that 'just works')

                                            – sawe
                                            Apr 11 '13 at 5:01











                                          • .slice() still works fine even if you have objects in your array: jsfiddle.net/edelman/k525g

                                            – Jason
                                            May 30 '13 at 19:49






                                          • 7





                                            @Jason but the objects are still pointing to the same object so changing one will change the other. jsfiddle.net/k525g/1

                                            – Samuel
                                            Jul 8 '13 at 14:39








                                          2




                                          2





                                          i get this error when i add this code to my page 'Uncaught RangeError: Maximum call stack size exceeded'

                                          – sawe
                                          Jan 21 '13 at 17:56







                                          i get this error when i add this code to my page 'Uncaught RangeError: Maximum call stack size exceeded'

                                          – sawe
                                          Jan 21 '13 at 17:56















                                          On Which Browser did you see this error??

                                          – sarvesh singh
                                          Apr 10 '13 at 12:12





                                          On Which Browser did you see this error??

                                          – sarvesh singh
                                          Apr 10 '13 at 12:12




                                          1




                                          1





                                          My apologies, this error occurs in chrome if arr1 is not declared. so i copy-pasted the above code, and i get the error, however, if i declare the array arr1, then i do not get the error. You could improve the answer by declaring arr1 just above arr2, i see there are quite a few of 'us' out there who did not recognise that we had to declare arr1 (partly because when i was evaluating your answer, i was in a rush and needed something that 'just works')

                                          – sawe
                                          Apr 11 '13 at 5:01





                                          My apologies, this error occurs in chrome if arr1 is not declared. so i copy-pasted the above code, and i get the error, however, if i declare the array arr1, then i do not get the error. You could improve the answer by declaring arr1 just above arr2, i see there are quite a few of 'us' out there who did not recognise that we had to declare arr1 (partly because when i was evaluating your answer, i was in a rush and needed something that 'just works')

                                          – sawe
                                          Apr 11 '13 at 5:01













                                          .slice() still works fine even if you have objects in your array: jsfiddle.net/edelman/k525g

                                          – Jason
                                          May 30 '13 at 19:49





                                          .slice() still works fine even if you have objects in your array: jsfiddle.net/edelman/k525g

                                          – Jason
                                          May 30 '13 at 19:49




                                          7




                                          7





                                          @Jason but the objects are still pointing to the same object so changing one will change the other. jsfiddle.net/k525g/1

                                          – Samuel
                                          Jul 8 '13 at 14:39





                                          @Jason but the objects are still pointing to the same object so changing one will change the other. jsfiddle.net/k525g/1

                                          – Samuel
                                          Jul 8 '13 at 14:39











                                          15














                                          From ES2015,



                                          var arr2 = [...arr1];





                                          share|improve this answer




























                                            15














                                            From ES2015,



                                            var arr2 = [...arr1];





                                            share|improve this answer


























                                              15












                                              15








                                              15







                                              From ES2015,



                                              var arr2 = [...arr1];





                                              share|improve this answer













                                              From ES2015,



                                              var arr2 = [...arr1];






                                              share|improve this answer












                                              share|improve this answer



                                              share|improve this answer










                                              answered Dec 24 '15 at 7:14









                                              Boopathi RajaaBoopathi Rajaa

                                              3,69612546




                                              3,69612546























                                                  14














                                                  I personally think Array.from is a more readable solution. By the way, just beware of its browser support.



                                                  //clone
                                                  let x = [1,2,3];
                                                  let y = Array.from(x);

                                                  //deep clone
                                                  let clone = arr => Array.from(arr,item => Array.isArray(item) ? clone(item) : item);
                                                  let x = [1,,[]];
                                                  let y = clone(x);





                                                  share|improve this answer





















                                                  • 1





                                                    Yes, this is very readable. The .slice() solution is completely unintuitive. Thanks for this.

                                                    – Banago
                                                    Jul 27 '16 at 14:46
















                                                  14














                                                  I personally think Array.from is a more readable solution. By the way, just beware of its browser support.



                                                  //clone
                                                  let x = [1,2,3];
                                                  let y = Array.from(x);

                                                  //deep clone
                                                  let clone = arr => Array.from(arr,item => Array.isArray(item) ? clone(item) : item);
                                                  let x = [1,,[]];
                                                  let y = clone(x);





                                                  share|improve this answer





















                                                  • 1





                                                    Yes, this is very readable. The .slice() solution is completely unintuitive. Thanks for this.

                                                    – Banago
                                                    Jul 27 '16 at 14:46














                                                  14












                                                  14








                                                  14







                                                  I personally think Array.from is a more readable solution. By the way, just beware of its browser support.



                                                  //clone
                                                  let x = [1,2,3];
                                                  let y = Array.from(x);

                                                  //deep clone
                                                  let clone = arr => Array.from(arr,item => Array.isArray(item) ? clone(item) : item);
                                                  let x = [1,,[]];
                                                  let y = clone(x);





                                                  share|improve this answer















                                                  I personally think Array.from is a more readable solution. By the way, just beware of its browser support.



                                                  //clone
                                                  let x = [1,2,3];
                                                  let y = Array.from(x);

                                                  //deep clone
                                                  let clone = arr => Array.from(arr,item => Array.isArray(item) ? clone(item) : item);
                                                  let x = [1,,[]];
                                                  let y = clone(x);






                                                  share|improve this answer














                                                  share|improve this answer



                                                  share|improve this answer








                                                  edited May 31 '16 at 6:37

























                                                  answered Mar 9 '16 at 12:01









                                                  LewisLewis

                                                  8,01174565




                                                  8,01174565








                                                  • 1





                                                    Yes, this is very readable. The .slice() solution is completely unintuitive. Thanks for this.

                                                    – Banago
                                                    Jul 27 '16 at 14:46














                                                  • 1





                                                    Yes, this is very readable. The .slice() solution is completely unintuitive. Thanks for this.

                                                    – Banago
                                                    Jul 27 '16 at 14:46








                                                  1




                                                  1





                                                  Yes, this is very readable. The .slice() solution is completely unintuitive. Thanks for this.

                                                  – Banago
                                                  Jul 27 '16 at 14:46





                                                  Yes, this is very readable. The .slice() solution is completely unintuitive. Thanks for this.

                                                  – Banago
                                                  Jul 27 '16 at 14:46











                                                  13














                                                  Important!



                                                  Most of answers here works for particular cases.



                                                  If you don't care about deep/nested objects and props use (ES6):



                                                  let clonedArray = [...array]



                                                  but if you want to do deep clone use this instead:



                                                  let cloneArray = JSON.parse(JSON.stringify(array))





                                                  For lodash users:



                                                  let clonedArray = _.clone(array) documentation



                                                  and



                                                  let clonedArray = _.cloneDeep(array) documentation






                                                  share|improve this answer






























                                                    13














                                                    Important!



                                                    Most of answers here works for particular cases.



                                                    If you don't care about deep/nested objects and props use (ES6):



                                                    let clonedArray = [...array]



                                                    but if you want to do deep clone use this instead:



                                                    let cloneArray = JSON.parse(JSON.stringify(array))





                                                    For lodash users:



                                                    let clonedArray = _.clone(array) documentation



                                                    and



                                                    let clonedArray = _.cloneDeep(array) documentation






                                                    share|improve this answer




























                                                      13












                                                      13








                                                      13







                                                      Important!



                                                      Most of answers here works for particular cases.



                                                      If you don't care about deep/nested objects and props use (ES6):



                                                      let clonedArray = [...array]



                                                      but if you want to do deep clone use this instead:



                                                      let cloneArray = JSON.parse(JSON.stringify(array))





                                                      For lodash users:



                                                      let clonedArray = _.clone(array) documentation



                                                      and



                                                      let clonedArray = _.cloneDeep(array) documentation






                                                      share|improve this answer















                                                      Important!



                                                      Most of answers here works for particular cases.



                                                      If you don't care about deep/nested objects and props use (ES6):



                                                      let clonedArray = [...array]



                                                      but if you want to do deep clone use this instead:



                                                      let cloneArray = JSON.parse(JSON.stringify(array))





                                                      For lodash users:



                                                      let clonedArray = _.clone(array) documentation



                                                      and



                                                      let clonedArray = _.cloneDeep(array) documentation







                                                      share|improve this answer














                                                      share|improve this answer



                                                      share|improve this answer








                                                      edited Sep 17 '18 at 15:31

























                                                      answered Aug 22 '18 at 14:46









                                                      ulouulou

                                                      1,37311626




                                                      1,37311626























                                                          11














                                                          If you are in an environment of ECMAScript 6, using the Spread Operator you could do it this way:






                                                          var arr1 = ['a','b','c'];
                                                          var arr2 = [...arr1]; //copy arr1
                                                          arr2.push('d');

                                                          console.log(arr1)
                                                          console.log(arr2)

                                                          <script src="http://www.wzvang.com/snippet/ignore_this_file.js"></script>








                                                          share|improve this answer






























                                                            11














                                                            If you are in an environment of ECMAScript 6, using the Spread Operator you could do it this way:






                                                            var arr1 = ['a','b','c'];
                                                            var arr2 = [...arr1]; //copy arr1
                                                            arr2.push('d');

                                                            console.log(arr1)
                                                            console.log(arr2)

                                                            <script src="http://www.wzvang.com/snippet/ignore_this_file.js"></script>








                                                            share|improve this answer




























                                                              11












                                                              11








                                                              11







                                                              If you are in an environment of ECMAScript 6, using the Spread Operator you could do it this way:






                                                              var arr1 = ['a','b','c'];
                                                              var arr2 = [...arr1]; //copy arr1
                                                              arr2.push('d');

                                                              console.log(arr1)
                                                              console.log(arr2)

                                                              <script src="http://www.wzvang.com/snippet/ignore_this_file.js"></script>








                                                              share|improve this answer















                                                              If you are in an environment of ECMAScript 6, using the Spread Operator you could do it this way:






                                                              var arr1 = ['a','b','c'];
                                                              var arr2 = [...arr1]; //copy arr1
                                                              arr2.push('d');

                                                              console.log(arr1)
                                                              console.log(arr2)

                                                              <script src="http://www.wzvang.com/snippet/ignore_this_file.js"></script>








                                                              var arr1 = ['a','b','c'];
                                                              var arr2 = [...arr1]; //copy arr1
                                                              arr2.push('d');

                                                              console.log(arr1)
                                                              console.log(arr2)

                                                              <script src="http://www.wzvang.com/snippet/ignore_this_file.js"></script>





                                                              var arr1 = ['a','b','c'];
                                                              var arr2 = [...arr1]; //copy arr1
                                                              arr2.push('d');

                                                              console.log(arr1)
                                                              console.log(arr2)

                                                              <script src="http://www.wzvang.com/snippet/ignore_this_file.js"></script>






                                                              share|improve this answer














                                                              share|improve this answer



                                                              share|improve this answer








                                                              edited Sep 6 '15 at 11:52









                                                              Peter Mortensen

                                                              13.8k1987113




                                                              13.8k1987113










                                                              answered Jul 3 '15 at 9:31









                                                              Walter Chapilliquen - wZVanGWalter Chapilliquen - wZVanG

                                                              7,37342751




                                                              7,37342751























                                                                  9














                                                                  Adding to the solution of array.slice(); be aware that if you have multidimensional array sub-arrays will be copied by references.
                                                                  What you can do is to loop and slice() each sub-array individually



                                                                  var arr = [[1,1,1],[2,2,2],[3,3,3]];
                                                                  var arr2 = arr.slice();

                                                                  arr2[0][1] = 55;
                                                                  console.log(arr2[0][1]);
                                                                  console.log(arr[0][1]);

                                                                  function arrCpy(arrSrc, arrDis){
                                                                  for(elm in arrSrc){
                                                                  arrDis.push(arrSrc[elm].slice());
                                                                  }
                                                                  }

                                                                  var arr3=;
                                                                  arrCpy(arr,arr3);

                                                                  arr3[1][1] = 77;

                                                                  console.log(arr3[1][1]);
                                                                  console.log(arr[1][1]);


                                                                  same things goes to array of objects, they will be copied by reference, you have to copy them manually






                                                                  share|improve this answer
























                                                                  • This answer deserves a spot near the top of the page! I was working with multidimensional sub arrays and could not follow why the inner arrays were always being copied by ref and not by val. This simple logic solved my problem. I would give you +100 if possible!

                                                                    – Mac
                                                                    Feb 16 '17 at 1:33
















                                                                  9














                                                                  Adding to the solution of array.slice(); be aware that if you have multidimensional array sub-arrays will be copied by references.
                                                                  What you can do is to loop and slice() each sub-array individually



                                                                  var arr = [[1,1,1],[2,2,2],[3,3,3]];
                                                                  var arr2 = arr.slice();

                                                                  arr2[0][1] = 55;
                                                                  console.log(arr2[0][1]);
                                                                  console.log(arr[0][1]);

                                                                  function arrCpy(arrSrc, arrDis){
                                                                  for(elm in arrSrc){
                                                                  arrDis.push(arrSrc[elm].slice());
                                                                  }
                                                                  }

                                                                  var arr3=;
                                                                  arrCpy(arr,arr3);

                                                                  arr3[1][1] = 77;

                                                                  console.log(arr3[1][1]);
                                                                  console.log(arr[1][1]);


                                                                  same things goes to array of objects, they will be copied by reference, you have to copy them manually






                                                                  share|improve this answer
























                                                                  • This answer deserves a spot near the top of the page! I was working with multidimensional sub arrays and could not follow why the inner arrays were always being copied by ref and not by val. This simple logic solved my problem. I would give you +100 if possible!

                                                                    – Mac
                                                                    Feb 16 '17 at 1:33














                                                                  9












                                                                  9








                                                                  9







                                                                  Adding to the solution of array.slice(); be aware that if you have multidimensional array sub-arrays will be copied by references.
                                                                  What you can do is to loop and slice() each sub-array individually



                                                                  var arr = [[1,1,1],[2,2,2],[3,3,3]];
                                                                  var arr2 = arr.slice();

                                                                  arr2[0][1] = 55;
                                                                  console.log(arr2[0][1]);
                                                                  console.log(arr[0][1]);

                                                                  function arrCpy(arrSrc, arrDis){
                                                                  for(elm in arrSrc){
                                                                  arrDis.push(arrSrc[elm].slice());
                                                                  }
                                                                  }

                                                                  var arr3=;
                                                                  arrCpy(arr,arr3);

                                                                  arr3[1][1] = 77;

                                                                  console.log(arr3[1][1]);
                                                                  console.log(arr[1][1]);


                                                                  same things goes to array of objects, they will be copied by reference, you have to copy them manually






                                                                  share|improve this answer













                                                                  Adding to the solution of array.slice(); be aware that if you have multidimensional array sub-arrays will be copied by references.
                                                                  What you can do is to loop and slice() each sub-array individually



                                                                  var arr = [[1,1,1],[2,2,2],[3,3,3]];
                                                                  var arr2 = arr.slice();

                                                                  arr2[0][1] = 55;
                                                                  console.log(arr2[0][1]);
                                                                  console.log(arr[0][1]);

                                                                  function arrCpy(arrSrc, arrDis){
                                                                  for(elm in arrSrc){
                                                                  arrDis.push(arrSrc[elm].slice());
                                                                  }
                                                                  }

                                                                  var arr3=;
                                                                  arrCpy(arr,arr3);

                                                                  arr3[1][1] = 77;

                                                                  console.log(arr3[1][1]);
                                                                  console.log(arr[1][1]);


                                                                  same things goes to array of objects, they will be copied by reference, you have to copy them manually







                                                                  share|improve this answer












                                                                  share|improve this answer



                                                                  share|improve this answer










                                                                  answered Apr 15 '14 at 13:40









                                                                  A.ZabenA.Zaben

                                                                  47457




                                                                  47457













                                                                  • This answer deserves a spot near the top of the page! I was working with multidimensional sub arrays and could not follow why the inner arrays were always being copied by ref and not by val. This simple logic solved my problem. I would give you +100 if possible!

                                                                    – Mac
                                                                    Feb 16 '17 at 1:33



















                                                                  • This answer deserves a spot near the top of the page! I was working with multidimensional sub arrays and could not follow why the inner arrays were always being copied by ref and not by val. This simple logic solved my problem. I would give you +100 if possible!

                                                                    – Mac
                                                                    Feb 16 '17 at 1:33

















                                                                  This answer deserves a spot near the top of the page! I was working with multidimensional sub arrays and could not follow why the inner arrays were always being copied by ref and not by val. This simple logic solved my problem. I would give you +100 if possible!

                                                                  – Mac
                                                                  Feb 16 '17 at 1:33





                                                                  This answer deserves a spot near the top of the page! I was working with multidimensional sub arrays and could not follow why the inner arrays were always being copied by ref and not by val. This simple logic solved my problem. I would give you +100 if possible!

                                                                  – Mac
                                                                  Feb 16 '17 at 1:33











                                                                  6














                                                                  As we know in Javascript arrays and objects are by reference, but what ways we can do copy the array without changing the original array later one?



                                                                  Here are few ways to do it:



                                                                  Imagine we have this array in your code:



                                                                  var arr = [1, 2, 3, 4, 5];


                                                                  1) Looping through the array in a function and return a new array, like this:



                                                                   function newArr(arr) {
                                                                  var i=0, res = ;
                                                                  while(i<arr.length){
                                                                  res.push(arr[i]);
                                                                  i++;
                                                                  }
                                                                  return res;
                                                                  }


                                                                  2) Using slice method, slice is for slicing part of the array, it will slice some part of your array without touching the original, in the slice, if don't specify the start and end of the array, it will slice the whole array and basically make a full copy of the array, so we can easily say:



                                                                  var arr2 = arr.slice(); // make a copy of the original array


                                                                  3) Also contact method, this is for merging two array, but we can just specify one of arrays and then this basically make a copy of the values in the new contacted array:



                                                                  var arr2 = arr.concat();


                                                                  4) Also stringify and parse method, it's not recommended, but can be an easy way to copy Array and Objects:



                                                                  var arr2 = JSON.parse(JSON.stringify(arr));


                                                                  5) Array.from method, this is not widely supported, before use check the support in different browsers:



                                                                  const arr2 = Array.from(arr);


                                                                  6) ECMA6 way, also not fully supported, but babelJs can help you if you want to transpile:



                                                                  const arr2 = [...arr];





                                                                  share|improve this answer






























                                                                    6














                                                                    As we know in Javascript arrays and objects are by reference, but what ways we can do copy the array without changing the original array later one?



                                                                    Here are few ways to do it:



                                                                    Imagine we have this array in your code:



                                                                    var arr = [1, 2, 3, 4, 5];


                                                                    1) Looping through the array in a function and return a new array, like this:



                                                                     function newArr(arr) {
                                                                    var i=0, res = ;
                                                                    while(i<arr.length){
                                                                    res.push(arr[i]);
                                                                    i++;
                                                                    }
                                                                    return res;
                                                                    }


                                                                    2) Using slice method, slice is for slicing part of the array, it will slice some part of your array without touching the original, in the slice, if don't specify the start and end of the array, it will slice the whole array and basically make a full copy of the array, so we can easily say:



                                                                    var arr2 = arr.slice(); // make a copy of the original array


                                                                    3) Also contact method, this is for merging two array, but we can just specify one of arrays and then this basically make a copy of the values in the new contacted array:



                                                                    var arr2 = arr.concat();


                                                                    4) Also stringify and parse method, it's not recommended, but can be an easy way to copy Array and Objects:



                                                                    var arr2 = JSON.parse(JSON.stringify(arr));


                                                                    5) Array.from method, this is not widely supported, before use check the support in different browsers:



                                                                    const arr2 = Array.from(arr);


                                                                    6) ECMA6 way, also not fully supported, but babelJs can help you if you want to transpile:



                                                                    const arr2 = [...arr];





                                                                    share|improve this answer




























                                                                      6












                                                                      6








                                                                      6







                                                                      As we know in Javascript arrays and objects are by reference, but what ways we can do copy the array without changing the original array later one?



                                                                      Here are few ways to do it:



                                                                      Imagine we have this array in your code:



                                                                      var arr = [1, 2, 3, 4, 5];


                                                                      1) Looping through the array in a function and return a new array, like this:



                                                                       function newArr(arr) {
                                                                      var i=0, res = ;
                                                                      while(i<arr.length){
                                                                      res.push(arr[i]);
                                                                      i++;
                                                                      }
                                                                      return res;
                                                                      }


                                                                      2) Using slice method, slice is for slicing part of the array, it will slice some part of your array without touching the original, in the slice, if don't specify the start and end of the array, it will slice the whole array and basically make a full copy of the array, so we can easily say:



                                                                      var arr2 = arr.slice(); // make a copy of the original array


                                                                      3) Also contact method, this is for merging two array, but we can just specify one of arrays and then this basically make a copy of the values in the new contacted array:



                                                                      var arr2 = arr.concat();


                                                                      4) Also stringify and parse method, it's not recommended, but can be an easy way to copy Array and Objects:



                                                                      var arr2 = JSON.parse(JSON.stringify(arr));


                                                                      5) Array.from method, this is not widely supported, before use check the support in different browsers:



                                                                      const arr2 = Array.from(arr);


                                                                      6) ECMA6 way, also not fully supported, but babelJs can help you if you want to transpile:



                                                                      const arr2 = [...arr];





                                                                      share|improve this answer















                                                                      As we know in Javascript arrays and objects are by reference, but what ways we can do copy the array without changing the original array later one?



                                                                      Here are few ways to do it:



                                                                      Imagine we have this array in your code:



                                                                      var arr = [1, 2, 3, 4, 5];


                                                                      1) Looping through the array in a function and return a new array, like this:



                                                                       function newArr(arr) {
                                                                      var i=0, res = ;
                                                                      while(i<arr.length){
                                                                      res.push(arr[i]);
                                                                      i++;
                                                                      }
                                                                      return res;
                                                                      }


                                                                      2) Using slice method, slice is for slicing part of the array, it will slice some part of your array without touching the original, in the slice, if don't specify the start and end of the array, it will slice the whole array and basically make a full copy of the array, so we can easily say:



                                                                      var arr2 = arr.slice(); // make a copy of the original array


                                                                      3) Also contact method, this is for merging two array, but we can just specify one of arrays and then this basically make a copy of the values in the new contacted array:



                                                                      var arr2 = arr.concat();


                                                                      4) Also stringify and parse method, it's not recommended, but can be an easy way to copy Array and Objects:



                                                                      var arr2 = JSON.parse(JSON.stringify(arr));


                                                                      5) Array.from method, this is not widely supported, before use check the support in different browsers:



                                                                      const arr2 = Array.from(arr);


                                                                      6) ECMA6 way, also not fully supported, but babelJs can help you if you want to transpile:



                                                                      const arr2 = [...arr];






                                                                      share|improve this answer














                                                                      share|improve this answer



                                                                      share|improve this answer








                                                                      edited May 1 '18 at 0:20

























                                                                      answered Mar 26 '17 at 2:35









                                                                      AlirezaAlireza

                                                                      51.9k13177124




                                                                      51.9k13177124























                                                                          4














                                                                          In my particular case I needed to ensure the array remained intact so this worked for me:



                                                                          // Empty array
                                                                          arr1.length = 0;
                                                                          // Add items from source array to target array
                                                                          for (var i = 0; i < arr2.length; i++) {
                                                                          arr1.push(arr2[i]);
                                                                          }





                                                                          share|improve this answer





















                                                                          • 2





                                                                            +1 for not adding obscuity to your code by calling a function that does exactly the same thing, but in a less obvious way. slice may be more efficient under the hood, but to anyone working on the code, this shows your intent. plus it makes it easier to optimise later, if you want to (for example) filter what you are copying. note however this does not handle deep copying, and the same internal objects are passed to the new array, by reference. This might be what you want to do, it might not.

                                                                            – unsynchronized
                                                                            Jun 30 '14 at 22:45
















                                                                          4














                                                                          In my particular case I needed to ensure the array remained intact so this worked for me:



                                                                          // Empty array
                                                                          arr1.length = 0;
                                                                          // Add items from source array to target array
                                                                          for (var i = 0; i < arr2.length; i++) {
                                                                          arr1.push(arr2[i]);
                                                                          }





                                                                          share|improve this answer





















                                                                          • 2





                                                                            +1 for not adding obscuity to your code by calling a function that does exactly the same thing, but in a less obvious way. slice may be more efficient under the hood, but to anyone working on the code, this shows your intent. plus it makes it easier to optimise later, if you want to (for example) filter what you are copying. note however this does not handle deep copying, and the same internal objects are passed to the new array, by reference. This might be what you want to do, it might not.

                                                                            – unsynchronized
                                                                            Jun 30 '14 at 22:45














                                                                          4












                                                                          4








                                                                          4







                                                                          In my particular case I needed to ensure the array remained intact so this worked for me:



                                                                          // Empty array
                                                                          arr1.length = 0;
                                                                          // Add items from source array to target array
                                                                          for (var i = 0; i < arr2.length; i++) {
                                                                          arr1.push(arr2[i]);
                                                                          }





                                                                          share|improve this answer















                                                                          In my particular case I needed to ensure the array remained intact so this worked for me:



                                                                          // Empty array
                                                                          arr1.length = 0;
                                                                          // Add items from source array to target array
                                                                          for (var i = 0; i < arr2.length; i++) {
                                                                          arr1.push(arr2[i]);
                                                                          }






                                                                          share|improve this answer














                                                                          share|improve this answer



                                                                          share|improve this answer








                                                                          edited Oct 29 '15 at 23:45









                                                                          fiat

                                                                          9,53546275




                                                                          9,53546275










                                                                          answered May 13 '14 at 18:20









                                                                          Brent KellerBrent Keller

                                                                          8601817




                                                                          8601817








                                                                          • 2





                                                                            +1 for not adding obscuity to your code by calling a function that does exactly the same thing, but in a less obvious way. slice may be more efficient under the hood, but to anyone working on the code, this shows your intent. plus it makes it easier to optimise later, if you want to (for example) filter what you are copying. note however this does not handle deep copying, and the same internal objects are passed to the new array, by reference. This might be what you want to do, it might not.

                                                                            – unsynchronized
                                                                            Jun 30 '14 at 22:45














                                                                          • 2





                                                                            +1 for not adding obscuity to your code by calling a function that does exactly the same thing, but in a less obvious way. slice may be more efficient under the hood, but to anyone working on the code, this shows your intent. plus it makes it easier to optimise later, if you want to (for example) filter what you are copying. note however this does not handle deep copying, and the same internal objects are passed to the new array, by reference. This might be what you want to do, it might not.

                                                                            – unsynchronized
                                                                            Jun 30 '14 at 22:45








                                                                          2




                                                                          2





                                                                          +1 for not adding obscuity to your code by calling a function that does exactly the same thing, but in a less obvious way. slice may be more efficient under the hood, but to anyone working on the code, this shows your intent. plus it makes it easier to optimise later, if you want to (for example) filter what you are copying. note however this does not handle deep copying, and the same internal objects are passed to the new array, by reference. This might be what you want to do, it might not.

                                                                          – unsynchronized
                                                                          Jun 30 '14 at 22:45





                                                                          +1 for not adding obscuity to your code by calling a function that does exactly the same thing, but in a less obvious way. slice may be more efficient under the hood, but to anyone working on the code, this shows your intent. plus it makes it easier to optimise later, if you want to (for example) filter what you are copying. note however this does not handle deep copying, and the same internal objects are passed to the new array, by reference. This might be what you want to do, it might not.

                                                                          – unsynchronized
                                                                          Jun 30 '14 at 22:45











                                                                          4














                                                                          Make copy of multidimensional array/object:



                                                                          function deepCopy(obj) {
                                                                          if (Object.prototype.toString.call(obj) === '[object Array]') {
                                                                          var out = , i = 0, len = obj.length;
                                                                          for ( ; i < len; i++ ) {
                                                                          out[i] = arguments.callee(obj[i]);
                                                                          }
                                                                          return out;
                                                                          }
                                                                          if (typeof obj === 'object') {
                                                                          var out = {}, i;
                                                                          for ( i in obj ) {
                                                                          out[i] = arguments.callee(obj[i]);
                                                                          }
                                                                          return out;
                                                                          }
                                                                          return obj;
                                                                          }


                                                                          Thanks to James Padolsey for this function.



                                                                          Source: Here






                                                                          share|improve this answer





















                                                                          • 1





                                                                            Nice , helped me. thank you.

                                                                            – f.n174
                                                                            Jan 2 '15 at 7:57











                                                                          • Thank you so much sir

                                                                            – Photonic
                                                                            Dec 8 '17 at 7:58
















                                                                          4














                                                                          Make copy of multidimensional array/object:



                                                                          function deepCopy(obj) {
                                                                          if (Object.prototype.toString.call(obj) === '[object Array]') {
                                                                          var out = , i = 0, len = obj.length;
                                                                          for ( ; i < len; i++ ) {
                                                                          out[i] = arguments.callee(obj[i]);
                                                                          }
                                                                          return out;
                                                                          }
                                                                          if (typeof obj === 'object') {
                                                                          var out = {}, i;
                                                                          for ( i in obj ) {
                                                                          out[i] = arguments.callee(obj[i]);
                                                                          }
                                                                          return out;
                                                                          }
                                                                          return obj;
                                                                          }


                                                                          Thanks to James Padolsey for this function.



                                                                          Source: Here






                                                                          share|improve this answer





















                                                                          • 1





                                                                            Nice , helped me. thank you.

                                                                            – f.n174
                                                                            Jan 2 '15 at 7:57











                                                                          • Thank you so much sir

                                                                            – Photonic
                                                                            Dec 8 '17 at 7:58














                                                                          4












                                                                          4








                                                                          4







                                                                          Make copy of multidimensional array/object:



                                                                          function deepCopy(obj) {
                                                                          if (Object.prototype.toString.call(obj) === '[object Array]') {
                                                                          var out = , i = 0, len = obj.length;
                                                                          for ( ; i < len; i++ ) {
                                                                          out[i] = arguments.callee(obj[i]);
                                                                          }
                                                                          return out;
                                                                          }
                                                                          if (typeof obj === 'object') {
                                                                          var out = {}, i;
                                                                          for ( i in obj ) {
                                                                          out[i] = arguments.callee(obj[i]);
                                                                          }
                                                                          return out;
                                                                          }
                                                                          return obj;
                                                                          }


                                                                          Thanks to James Padolsey for this function.



                                                                          Source: Here






                                                                          share|improve this answer















                                                                          Make copy of multidimensional array/object:



                                                                          function deepCopy(obj) {
                                                                          if (Object.prototype.toString.call(obj) === '[object Array]') {
                                                                          var out = , i = 0, len = obj.length;
                                                                          for ( ; i < len; i++ ) {
                                                                          out[i] = arguments.callee(obj[i]);
                                                                          }
                                                                          return out;
                                                                          }
                                                                          if (typeof obj === 'object') {
                                                                          var out = {}, i;
                                                                          for ( i in obj ) {
                                                                          out[i] = arguments.callee(obj[i]);
                                                                          }
                                                                          return out;
                                                                          }
                                                                          return obj;
                                                                          }


                                                                          Thanks to James Padolsey for this function.



                                                                          Source: Here







                                                                          share|improve this answer














                                                                          share|improve this answer



                                                                          share|improve this answer








                                                                          edited Feb 6 '17 at 7:13









                                                                          heena Jethva

                                                                          554




                                                                          554










                                                                          answered Jul 22 '14 at 12:15









                                                                          inkink

                                                                          5091522




                                                                          5091522








                                                                          • 1





                                                                            Nice , helped me. thank you.

                                                                            – f.n174
                                                                            Jan 2 '15 at 7:57











                                                                          • Thank you so much sir

                                                                            – Photonic
                                                                            Dec 8 '17 at 7:58














                                                                          • 1





                                                                            Nice , helped me. thank you.

                                                                            – f.n174
                                                                            Jan 2 '15 at 7:57











                                                                          • Thank you so much sir

                                                                            – Photonic
                                                                            Dec 8 '17 at 7:58








                                                                          1




                                                                          1





                                                                          Nice , helped me. thank you.

                                                                          – f.n174
                                                                          Jan 2 '15 at 7:57





                                                                          Nice , helped me. thank you.

                                                                          – f.n174
                                                                          Jan 2 '15 at 7:57













                                                                          Thank you so much sir

                                                                          – Photonic
                                                                          Dec 8 '17 at 7:58





                                                                          Thank you so much sir

                                                                          – Photonic
                                                                          Dec 8 '17 at 7:58











                                                                          4














                                                                          Dan, no need to use fancy tricks. All you need to do is make copy of arr1 by doing this.






                                                                          var arr2 = new Array(arr1);





                                                                          Now arr1 and arr2 are two different array variables stored in separate stacks.
                                                                          Check this out on jsfiddle.






                                                                          share|improve this answer
























                                                                          • This doesn't copy the array. It creates an array with one element that references the original (i.e. var arr2 = [arr1];).

                                                                            – Timothy003
                                                                            Nov 21 '18 at 23:25
















                                                                          4














                                                                          Dan, no need to use fancy tricks. All you need to do is make copy of arr1 by doing this.






                                                                          var arr2 = new Array(arr1);





                                                                          Now arr1 and arr2 are two different array variables stored in separate stacks.
                                                                          Check this out on jsfiddle.






                                                                          share|improve this answer
























                                                                          • This doesn't copy the array. It creates an array with one element that references the original (i.e. var arr2 = [arr1];).

                                                                            – Timothy003
                                                                            Nov 21 '18 at 23:25














                                                                          4












                                                                          4








                                                                          4







                                                                          Dan, no need to use fancy tricks. All you need to do is make copy of arr1 by doing this.






                                                                          var arr2 = new Array(arr1);





                                                                          Now arr1 and arr2 are two different array variables stored in separate stacks.
                                                                          Check this out on jsfiddle.






                                                                          share|improve this answer













                                                                          Dan, no need to use fancy tricks. All you need to do is make copy of arr1 by doing this.






                                                                          var arr2 = new Array(arr1);





                                                                          Now arr1 and arr2 are two different array variables stored in separate stacks.
                                                                          Check this out on jsfiddle.






                                                                          var arr2 = new Array(arr1);





                                                                          var arr2 = new Array(arr1);






                                                                          share|improve this answer












                                                                          share|improve this answer



                                                                          share|improve this answer










                                                                          answered May 18 '18 at 15:05









                                                                          DragoRaptorDragoRaptor

                                                                          37228




                                                                          37228













                                                                          • This doesn't copy the array. It creates an array with one element that references the original (i.e. var arr2 = [arr1];).

                                                                            – Timothy003
                                                                            Nov 21 '18 at 23:25



















                                                                          • This doesn't copy the array. It creates an array with one element that references the original (i.e. var arr2 = [arr1];).

                                                                            – Timothy003
                                                                            Nov 21 '18 at 23:25

















                                                                          This doesn't copy the array. It creates an array with one element that references the original (i.e. var arr2 = [arr1];).

                                                                          – Timothy003
                                                                          Nov 21 '18 at 23:25





                                                                          This doesn't copy the array. It creates an array with one element that references the original (i.e. var arr2 = [arr1];).

                                                                          – Timothy003
                                                                          Nov 21 '18 at 23:25











                                                                          3














                                                                          When we want to copy an array using the assignment operator ( = ) it doesn't create a copy it merely copies the pointer/reference to the array. For example:






                                                                          const oldArr = [1,2,3];

                                                                          const newArr = oldArr; // now oldArr points to the same place in memory

                                                                          console.log(oldArr === newArr); // Points to the same place in memory thus is true

                                                                          const copy = [1,2,3];

                                                                          console.log(copy === newArr); // Doesn't point to the same place in memory and thus is false





                                                                          Often when we transform data we want to keep our initial datastructure (e.g. Array) intact. We do this by making a exact copy of our array so this one can be transformed while the initial one stays intact.



                                                                          Ways of copying an array:






                                                                          const oldArr = [1,2,3];

                                                                          // Uses the spread operator to spread out old values into the new array literal
                                                                          const newArr1 = [...oldArr];

                                                                          // Slice with no arguments returns the newly copied Array
                                                                          const newArr2 = oldArr.slice();

                                                                          // Map applies the callback to every element in the array and returns a new array
                                                                          const newArr3 = oldArr.map((el) => el);

                                                                          // Concat is used to merge arrays and returns a new array. Concat with no args copies an array
                                                                          const newArr4 = oldArr.concat();

                                                                          // Object.assign can be used to transfer all the properties into a new array literal
                                                                          const newArr5 = Object.assign(, oldArr);

                                                                          // Creating via the Array constructor using the new keyword
                                                                          const newArr6 = new Array(...oldArr);

                                                                          // For loop
                                                                          function clone(base) {
                                                                          const newArray = ;
                                                                          for(let i= 0; i < base.length; i++) {
                                                                          newArray[i] = base[i];
                                                                          }
                                                                          return newArray;
                                                                          }

                                                                          const newArr7 = clone(oldArr);

                                                                          console.log(newArr1, newArr2, newArr3, newArr4, newArr5, newArr6, newArr7);





                                                                          Be careful when arrays or objects are nested!:



                                                                          When arrays are nested the values are copied by reference. Here is an example of how this could lead to issues:






                                                                          let arr1 = [1,2,[1,2,3]]

                                                                          let arr2 = [...arr1];

                                                                          arr2[2][0] = 5; // we change arr2

                                                                          console.log(arr1); // arr1 is also changed because the array inside arr1 was copied by reference





                                                                          So don't use these methods when there are objects or arrays inside your array you want to copy. i.e. Use these methods on arrays of primitives only.



                                                                          If you do want to deepclone a javascript array use JSON.parse in conjunction with JSON.stringify, like this:






                                                                          let arr1 = [1,2,[1,2,3]]

                                                                          let arr2 = JSON.parse(JSON.stringify(arr1)) ;

                                                                          arr2[2][0] = 5;

                                                                          console.log(arr1); // now I'm not modified because I'm a deep clone





                                                                          Performance of copying:



                                                                          So which one do we choose for optimal performance. It turns out that the most verbose method, the for loop has the highest performance. Use the for loop for really CPU intensive copying (large/many arrays).



                                                                          After that the .slice() method also has decent performance and is also less verbose and easier for the programmer to implement. I suggest to use .slice() for your everyday copying of arrays which aren't very CPU intensive. Also avoid using the JSON.parse(JSON.stringify(arr)) (lots of overhead) if no deep clone is required and performance is an issue.



                                                                          Source performance test






                                                                          share|improve this answer






























                                                                            3














                                                                            When we want to copy an array using the assignment operator ( = ) it doesn't create a copy it merely copies the pointer/reference to the array. For example:






                                                                            const oldArr = [1,2,3];

                                                                            const newArr = oldArr; // now oldArr points to the same place in memory

                                                                            console.log(oldArr === newArr); // Points to the same place in memory thus is true

                                                                            const copy = [1,2,3];

                                                                            console.log(copy === newArr); // Doesn't point to the same place in memory and thus is false





                                                                            Often when we transform data we want to keep our initial datastructure (e.g. Array) intact. We do this by making a exact copy of our array so this one can be transformed while the initial one stays intact.



                                                                            Ways of copying an array:






                                                                            const oldArr = [1,2,3];

                                                                            // Uses the spread operator to spread out old values into the new array literal
                                                                            const newArr1 = [...oldArr];

                                                                            // Slice with no arguments returns the newly copied Array
                                                                            const newArr2 = oldArr.slice();

                                                                            // Map applies the callback to every element in the array and returns a new array
                                                                            const newArr3 = oldArr.map((el) => el);

                                                                            // Concat is used to merge arrays and returns a new array. Concat with no args copies an array
                                                                            const newArr4 = oldArr.concat();

                                                                            // Object.assign can be used to transfer all the properties into a new array literal
                                                                            const newArr5 = Object.assign(, oldArr);

                                                                            // Creating via the Array constructor using the new keyword
                                                                            const newArr6 = new Array(...oldArr);

                                                                            // For loop
                                                                            function clone(base) {
                                                                            const newArray = ;
                                                                            for(let i= 0; i < base.length; i++) {
                                                                            newArray[i] = base[i];
                                                                            }
                                                                            return newArray;
                                                                            }

                                                                            const newArr7 = clone(oldArr);

                                                                            console.log(newArr1, newArr2, newArr3, newArr4, newArr5, newArr6, newArr7);





                                                                            Be careful when arrays or objects are nested!:



                                                                            When arrays are nested the values are copied by reference. Here is an example of how this could lead to issues:






                                                                            let arr1 = [1,2,[1,2,3]]

                                                                            let arr2 = [...arr1];

                                                                            arr2[2][0] = 5; // we change arr2

                                                                            console.log(arr1); // arr1 is also changed because the array inside arr1 was copied by reference





                                                                            So don't use these methods when there are objects or arrays inside your array you want to copy. i.e. Use these methods on arrays of primitives only.



                                                                            If you do want to deepclone a javascript array use JSON.parse in conjunction with JSON.stringify, like this:






                                                                            let arr1 = [1,2,[1,2,3]]

                                                                            let arr2 = JSON.parse(JSON.stringify(arr1)) ;

                                                                            arr2[2][0] = 5;

                                                                            console.log(arr1); // now I'm not modified because I'm a deep clone





                                                                            Performance of copying:



                                                                            So which one do we choose for optimal performance. It turns out that the most verbose method, the for loop has the highest performance. Use the for loop for really CPU intensive copying (large/many arrays).



                                                                            After that the .slice() method also has decent performance and is also less verbose and easier for the programmer to implement. I suggest to use .slice() for your everyday copying of arrays which aren't very CPU intensive. Also avoid using the JSON.parse(JSON.stringify(arr)) (lots of overhead) if no deep clone is required and performance is an issue.



                                                                            Source performance test






                                                                            share|improve this answer




























                                                                              3












                                                                              3








                                                                              3







                                                                              When we want to copy an array using the assignment operator ( = ) it doesn't create a copy it merely copies the pointer/reference to the array. For example:






                                                                              const oldArr = [1,2,3];

                                                                              const newArr = oldArr; // now oldArr points to the same place in memory

                                                                              console.log(oldArr === newArr); // Points to the same place in memory thus is true

                                                                              const copy = [1,2,3];

                                                                              console.log(copy === newArr); // Doesn't point to the same place in memory and thus is false





                                                                              Often when we transform data we want to keep our initial datastructure (e.g. Array) intact. We do this by making a exact copy of our array so this one can be transformed while the initial one stays intact.



                                                                              Ways of copying an array:






                                                                              const oldArr = [1,2,3];

                                                                              // Uses the spread operator to spread out old values into the new array literal
                                                                              const newArr1 = [...oldArr];

                                                                              // Slice with no arguments returns the newly copied Array
                                                                              const newArr2 = oldArr.slice();

                                                                              // Map applies the callback to every element in the array and returns a new array
                                                                              const newArr3 = oldArr.map((el) => el);

                                                                              // Concat is used to merge arrays and returns a new array. Concat with no args copies an array
                                                                              const newArr4 = oldArr.concat();

                                                                              // Object.assign can be used to transfer all the properties into a new array literal
                                                                              const newArr5 = Object.assign(, oldArr);

                                                                              // Creating via the Array constructor using the new keyword
                                                                              const newArr6 = new Array(...oldArr);

                                                                              // For loop
                                                                              function clone(base) {
                                                                              const newArray = ;
                                                                              for(let i= 0; i < base.length; i++) {
                                                                              newArray[i] = base[i];
                                                                              }
                                                                              return newArray;
                                                                              }

                                                                              const newArr7 = clone(oldArr);

                                                                              console.log(newArr1, newArr2, newArr3, newArr4, newArr5, newArr6, newArr7);





                                                                              Be careful when arrays or objects are nested!:



                                                                              When arrays are nested the values are copied by reference. Here is an example of how this could lead to issues:






                                                                              let arr1 = [1,2,[1,2,3]]

                                                                              let arr2 = [...arr1];

                                                                              arr2[2][0] = 5; // we change arr2

                                                                              console.log(arr1); // arr1 is also changed because the array inside arr1 was copied by reference





                                                                              So don't use these methods when there are objects or arrays inside your array you want to copy. i.e. Use these methods on arrays of primitives only.



                                                                              If you do want to deepclone a javascript array use JSON.parse in conjunction with JSON.stringify, like this:






                                                                              let arr1 = [1,2,[1,2,3]]

                                                                              let arr2 = JSON.parse(JSON.stringify(arr1)) ;

                                                                              arr2[2][0] = 5;

                                                                              console.log(arr1); // now I'm not modified because I'm a deep clone





                                                                              Performance of copying:



                                                                              So which one do we choose for optimal performance. It turns out that the most verbose method, the for loop has the highest performance. Use the for loop for really CPU intensive copying (large/many arrays).



                                                                              After that the .slice() method also has decent performance and is also less verbose and easier for the programmer to implement. I suggest to use .slice() for your everyday copying of arrays which aren't very CPU intensive. Also avoid using the JSON.parse(JSON.stringify(arr)) (lots of overhead) if no deep clone is required and performance is an issue.



                                                                              Source performance test






                                                                              share|improve this answer















                                                                              When we want to copy an array using the assignment operator ( = ) it doesn't create a copy it merely copies the pointer/reference to the array. For example:






                                                                              const oldArr = [1,2,3];

                                                                              const newArr = oldArr; // now oldArr points to the same place in memory

                                                                              console.log(oldArr === newArr); // Points to the same place in memory thus is true

                                                                              const copy = [1,2,3];

                                                                              console.log(copy === newArr); // Doesn't point to the same place in memory and thus is false





                                                                              Often when we transform data we want to keep our initial datastructure (e.g. Array) intact. We do this by making a exact copy of our array so this one can be transformed while the initial one stays intact.



                                                                              Ways of copying an array:






                                                                              const oldArr = [1,2,3];

                                                                              // Uses the spread operator to spread out old values into the new array literal
                                                                              const newArr1 = [...oldArr];

                                                                              // Slice with no arguments returns the newly copied Array
                                                                              const newArr2 = oldArr.slice();

                                                                              // Map applies the callback to every element in the array and returns a new array
                                                                              const newArr3 = oldArr.map((el) => el);

                                                                              // Concat is used to merge arrays and returns a new array. Concat with no args copies an array
                                                                              const newArr4 = oldArr.concat();

                                                                              // Object.assign can be used to transfer all the properties into a new array literal
                                                                              const newArr5 = Object.assign(, oldArr);

                                                                              // Creating via the Array constructor using the new keyword
                                                                              const newArr6 = new Array(...oldArr);

                                                                              // For loop
                                                                              function clone(base) {
                                                                              const newArray = ;
                                                                              for(let i= 0; i < base.length; i++) {
                                                                              newArray[i] = base[i];
                                                                              }
                                                                              return newArray;
                                                                              }

                                                                              const newArr7 = clone(oldArr);

                                                                              console.log(newArr1, newArr2, newArr3, newArr4, newArr5, newArr6, newArr7);





                                                                              Be careful when arrays or objects are nested!:



                                                                              When arrays are nested the values are copied by reference. Here is an example of how this could lead to issues:






                                                                              let arr1 = [1,2,[1,2,3]]

                                                                              let arr2 = [...arr1];

                                                                              arr2[2][0] = 5; // we change arr2

                                                                              console.log(arr1); // arr1 is also changed because the array inside arr1 was copied by reference





                                                                              So don't use these methods when there are objects or arrays inside your array you want to copy. i.e. Use these methods on arrays of primitives only.



                                                                              If you do want to deepclone a javascript array use JSON.parse in conjunction with JSON.stringify, like this:






                                                                              let arr1 = [1,2,[1,2,3]]

                                                                              let arr2 = JSON.parse(JSON.stringify(arr1)) ;

                                                                              arr2[2][0] = 5;

                                                                              console.log(arr1); // now I'm not modified because I'm a deep clone





                                                                              Performance of copying:



                                                                              So which one do we choose for optimal performance. It turns out that the most verbose method, the for loop has the highest performance. Use the for loop for really CPU intensive copying (large/many arrays).



                                                                              After that the .slice() method also has decent performance and is also less verbose and easier for the programmer to implement. I suggest to use .slice() for your everyday copying of arrays which aren't very CPU intensive. Also avoid using the JSON.parse(JSON.stringify(arr)) (lots of overhead) if no deep clone is required and performance is an issue.



                                                                              Source performance test






                                                                              const oldArr = [1,2,3];

                                                                              const newArr = oldArr; // now oldArr points to the same place in memory

                                                                              console.log(oldArr === newArr); // Points to the same place in memory thus is true

                                                                              const copy = [1,2,3];

                                                                              console.log(copy === newArr); // Doesn't point to the same place in memory and thus is false





                                                                              const oldArr = [1,2,3];

                                                                              const newArr = oldArr; // now oldArr points to the same place in memory

                                                                              console.log(oldArr === newArr); // Points to the same place in memory thus is true

                                                                              const copy = [1,2,3];

                                                                              console.log(copy === newArr); // Doesn't point to the same place in memory and thus is false





                                                                              const oldArr = [1,2,3];

                                                                              // Uses the spread operator to spread out old values into the new array literal
                                                                              const newArr1 = [...oldArr];

                                                                              // Slice with no arguments returns the newly copied Array
                                                                              const newArr2 = oldArr.slice();

                                                                              // Map applies the callback to every element in the array and returns a new array
                                                                              const newArr3 = oldArr.map((el) => el);

                                                                              // Concat is used to merge arrays and returns a new array. Concat with no args copies an array
                                                                              const newArr4 = oldArr.concat();

                                                                              // Object.assign can be used to transfer all the properties into a new array literal
                                                                              const newArr5 = Object.assign(, oldArr);

                                                                              // Creating via the Array constructor using the new keyword
                                                                              const newArr6 = new Array(...oldArr);

                                                                              // For loop
                                                                              function clone(base) {
                                                                              const newArray = ;
                                                                              for(let i= 0; i < base.length; i++) {
                                                                              newArray[i] = base[i];
                                                                              }
                                                                              return newArray;
                                                                              }

                                                                              const newArr7 = clone(oldArr);

                                                                              console.log(newArr1, newArr2, newArr3, newArr4, newArr5, newArr6, newArr7);





                                                                              const oldArr = [1,2,3];

                                                                              // Uses the spread operator to spread out old values into the new array literal
                                                                              const newArr1 = [...oldArr];

                                                                              // Slice with no arguments returns the newly copied Array
                                                                              const newArr2 = oldArr.slice();

                                                                              // Map applies the callback to every element in the array and returns a new array
                                                                              const newArr3 = oldArr.map((el) => el);

                                                                              // Concat is used to merge arrays and returns a new array. Concat with no args copies an array
                                                                              const newArr4 = oldArr.concat();

                                                                              // Object.assign can be used to transfer all the properties into a new array literal
                                                                              const newArr5 = Object.assign(, oldArr);

                                                                              // Creating via the Array constructor using the new keyword
                                                                              const newArr6 = new Array(...oldArr);

                                                                              // For loop
                                                                              function clone(base) {
                                                                              const newArray = ;
                                                                              for(let i= 0; i < base.length; i++) {
                                                                              newArray[i] = base[i];
                                                                              }
                                                                              return newArray;
                                                                              }

                                                                              const newArr7 = clone(oldArr);

                                                                              console.log(newArr1, newArr2, newArr3, newArr4, newArr5, newArr6, newArr7);





                                                                              let arr1 = [1,2,[1,2,3]]

                                                                              let arr2 = [...arr1];

                                                                              arr2[2][0] = 5; // we change arr2

                                                                              console.log(arr1); // arr1 is also changed because the array inside arr1 was copied by reference





                                                                              let arr1 = [1,2,[1,2,3]]

                                                                              let arr2 = [...arr1];

                                                                              arr2[2][0] = 5; // we change arr2

                                                                              console.log(arr1); // arr1 is also changed because the array inside arr1 was copied by reference





                                                                              let arr1 = [1,2,[1,2,3]]

                                                                              let arr2 = JSON.parse(JSON.stringify(arr1)) ;

                                                                              arr2[2][0] = 5;

                                                                              console.log(arr1); // now I'm not modified because I'm a deep clone





                                                                              let arr1 = [1,2,[1,2,3]]

                                                                              let arr2 = JSON.parse(JSON.stringify(arr1)) ;

                                                                              arr2[2][0] = 5;

                                                                              console.log(arr1); // now I'm not modified because I'm a deep clone






                                                                              share|improve this answer














                                                                              share|improve this answer



                                                                              share|improve this answer








                                                                              edited Aug 9 '18 at 22:46

























                                                                              answered Aug 6 '18 at 10:06









                                                                              Willem van der VeenWillem van der Veen

                                                                              5,32032737




                                                                              5,32032737























                                                                                  2














                                                                                  If you want to make a new copy of an object or array, you must explicitly copy the properties of the object or the elements of the array, for example:



                                                                                  var arr1 = ['a','b','c'];
                                                                                  var arr2 = ;

                                                                                  for (var i=0; i < arr1.length; i++) {
                                                                                  arr2[i] = arr1[i];
                                                                                  }


                                                                                  You can search for more information on Google about immutable primitive values and mutable object references.






                                                                                  share|improve this answer





















                                                                                  • 1





                                                                                    You don't have to explicitly copy the properties of the objects of the array. See Chtiwi Malek's answer.

                                                                                    – Magne
                                                                                    Jun 4 '14 at 14:30


















                                                                                  2














                                                                                  If you want to make a new copy of an object or array, you must explicitly copy the properties of the object or the elements of the array, for example:



                                                                                  var arr1 = ['a','b','c'];
                                                                                  var arr2 = ;

                                                                                  for (var i=0; i < arr1.length; i++) {
                                                                                  arr2[i] = arr1[i];
                                                                                  }


                                                                                  You can search for more information on Google about immutable primitive values and mutable object references.






                                                                                  share|improve this answer





















                                                                                  • 1





                                                                                    You don't have to explicitly copy the properties of the objects of the array. See Chtiwi Malek's answer.

                                                                                    – Magne
                                                                                    Jun 4 '14 at 14:30
















                                                                                  2












                                                                                  2








                                                                                  2







                                                                                  If you want to make a new copy of an object or array, you must explicitly copy the properties of the object or the elements of the array, for example:



                                                                                  var arr1 = ['a','b','c'];
                                                                                  var arr2 = ;

                                                                                  for (var i=0; i < arr1.length; i++) {
                                                                                  arr2[i] = arr1[i];
                                                                                  }


                                                                                  You can search for more information on Google about immutable primitive values and mutable object references.






                                                                                  share|improve this answer















                                                                                  If you want to make a new copy of an object or array, you must explicitly copy the properties of the object or the elements of the array, for example:



                                                                                  var arr1 = ['a','b','c'];
                                                                                  var arr2 = ;

                                                                                  for (var i=0; i < arr1.length; i++) {
                                                                                  arr2[i] = arr1[i];
                                                                                  }


                                                                                  You can search for more information on Google about immutable primitive values and mutable object references.







                                                                                  share|improve this answer














                                                                                  share|improve this answer



                                                                                  share|improve this answer








                                                                                  edited Sep 6 '15 at 11:32









                                                                                  Peter Mortensen

                                                                                  13.8k1987113




                                                                                  13.8k1987113










                                                                                  answered Sep 20 '11 at 13:45









                                                                                  SotirisSotiris

                                                                                  30.9k94079




                                                                                  30.9k94079








                                                                                  • 1





                                                                                    You don't have to explicitly copy the properties of the objects of the array. See Chtiwi Malek's answer.

                                                                                    – Magne
                                                                                    Jun 4 '14 at 14:30
















                                                                                  • 1





                                                                                    You don't have to explicitly copy the properties of the objects of the array. See Chtiwi Malek's answer.

                                                                                    – Magne
                                                                                    Jun 4 '14 at 14:30










                                                                                  1




                                                                                  1





                                                                                  You don't have to explicitly copy the properties of the objects of the array. See Chtiwi Malek's answer.

                                                                                  – Magne
                                                                                  Jun 4 '14 at 14:30







                                                                                  You don't have to explicitly copy the properties of the objects of the array. See Chtiwi Malek's answer.

                                                                                  – Magne
                                                                                  Jun 4 '14 at 14:30













                                                                                  2














                                                                                  Using jQuery deep copy could be made as following:



                                                                                  var arr2 = $.extend(true, , arr1);





                                                                                  share|improve this answer




























                                                                                    2














                                                                                    Using jQuery deep copy could be made as following:



                                                                                    var arr2 = $.extend(true, , arr1);





                                                                                    share|improve this answer


























                                                                                      2












                                                                                      2








                                                                                      2







                                                                                      Using jQuery deep copy could be made as following:



                                                                                      var arr2 = $.extend(true, , arr1);





                                                                                      share|improve this answer













                                                                                      Using jQuery deep copy could be made as following:



                                                                                      var arr2 = $.extend(true, , arr1);






                                                                                      share|improve this answer












                                                                                      share|improve this answer



                                                                                      share|improve this answer










                                                                                      answered Jan 12 '17 at 19:26









                                                                                      Alex TsurikaAlex Tsurika

                                                                                      584613




                                                                                      584613























                                                                                          2














                                                                                          You can also use ES6 spread operator to copy Array



                                                                                          var arr=[2,3,4,5];
                                                                                          var copyArr=[...arr];





                                                                                          share|improve this answer




























                                                                                            2














                                                                                            You can also use ES6 spread operator to copy Array



                                                                                            var arr=[2,3,4,5];
                                                                                            var copyArr=[...arr];





                                                                                            share|improve this answer


























                                                                                              2












                                                                                              2








                                                                                              2







                                                                                              You can also use ES6 spread operator to copy Array



                                                                                              var arr=[2,3,4,5];
                                                                                              var copyArr=[...arr];





                                                                                              share|improve this answer













                                                                                              You can also use ES6 spread operator to copy Array



                                                                                              var arr=[2,3,4,5];
                                                                                              var copyArr=[...arr];






                                                                                              share|improve this answer












                                                                                              share|improve this answer



                                                                                              share|improve this answer










                                                                                              answered Jun 30 '17 at 19:16









                                                                                              ankur kushwahaankur kushwaha

                                                                                              28317




                                                                                              28317























                                                                                                  2














                                                                                                  Here are few more way to copy:






                                                                                                  const array = [1,2,3,4];

                                                                                                  const arrayCopy1 = Object.values(array);
                                                                                                  const arrayCopy2 = Object.assign(, array);
                                                                                                  const arrayCopy3 = array.map(i => i);
                                                                                                  const arrayCopy4 = Array.of(...array );








                                                                                                  share|improve this answer




























                                                                                                    2














                                                                                                    Here are few more way to copy:






                                                                                                    const array = [1,2,3,4];

                                                                                                    const arrayCopy1 = Object.values(array);
                                                                                                    const arrayCopy2 = Object.assign(, array);
                                                                                                    const arrayCopy3 = array.map(i => i);
                                                                                                    const arrayCopy4 = Array.of(...array );








                                                                                                    share|improve this answer


























                                                                                                      2












                                                                                                      2








                                                                                                      2







                                                                                                      Here are few more way to copy:






                                                                                                      const array = [1,2,3,4];

                                                                                                      const arrayCopy1 = Object.values(array);
                                                                                                      const arrayCopy2 = Object.assign(, array);
                                                                                                      const arrayCopy3 = array.map(i => i);
                                                                                                      const arrayCopy4 = Array.of(...array );








                                                                                                      share|improve this answer













                                                                                                      Here are few more way to copy:






                                                                                                      const array = [1,2,3,4];

                                                                                                      const arrayCopy1 = Object.values(array);
                                                                                                      const arrayCopy2 = Object.assign(, array);
                                                                                                      const arrayCopy3 = array.map(i => i);
                                                                                                      const arrayCopy4 = Array.of(...array );








                                                                                                      const array = [1,2,3,4];

                                                                                                      const arrayCopy1 = Object.values(array);
                                                                                                      const arrayCopy2 = Object.assign(, array);
                                                                                                      const arrayCopy3 = array.map(i => i);
                                                                                                      const arrayCopy4 = Array.of(...array );





                                                                                                      const array = [1,2,3,4];

                                                                                                      const arrayCopy1 = Object.values(array);
                                                                                                      const arrayCopy2 = Object.assign(, array);
                                                                                                      const arrayCopy3 = array.map(i => i);
                                                                                                      const arrayCopy4 = Array.of(...array );






                                                                                                      share|improve this answer












                                                                                                      share|improve this answer



                                                                                                      share|improve this answer










                                                                                                      answered Apr 12 '18 at 7:00









                                                                                                      ganesh phirkeganesh phirke

                                                                                                      687




                                                                                                      687























                                                                                                          2














                                                                                                          Quick Examples:




                                                                                                          1. If elements in the array are primitive types (string, number, etc.)





                                                                                                          var arr1 = ['a','b','c'];
                                                                                                          // arr1 and arr2 are independent and primitive elements are stored in
                                                                                                          // different places in the memory
                                                                                                          var arr2 = arr1.slice();
                                                                                                          arr2.push('d');
                                                                                                          console.log(arr1); // [ 'a', 'b', 'c' ]
                                                                                                          console.log(arr2); // [ 'a', 'b', 'c', 'd' ]






                                                                                                          1. If elements in the array are object literals, another array ({}, )





                                                                                                          var arr1 = [{ x: 'a', y: 'b'}, [1, 2], [3, 4]];
                                                                                                          // arr1 and arr2 are independent and reference's/addresses are stored in different
                                                                                                          // places in the memory. But those reference's/addresses points to some common place
                                                                                                          // in the memory.
                                                                                                          var arr2 = arr1.slice();
                                                                                                          arr2.pop(); // OK - don't affect arr1 bcos only the address in the arr2 is
                                                                                                          // deleted not the data pointed by that address
                                                                                                          arr2[0].x = 'z'; // not OK - affect arr1 bcos changes made in the common area
                                                                                                          // pointed by the addresses in both arr1 and arr2
                                                                                                          arr2[1][0] = 9; // not OK - same above reason

                                                                                                          console.log(arr1); // [ { x: 'z', y: 'b' }, [ 9, 2 ], [ 3, 4 ] ]
                                                                                                          console.log(arr2); // [ { x: 'z', y: 'b' }, [ 9, 2 ] ]







                                                                                                          1. Solution for 2: Deep Copy by element by element





                                                                                                          var arr1 = [{ x: 'a', y: 'b'}, [1, 2], [3, 4]];
                                                                                                          arr2 = JSON.parse(JSON.stringify(arr1));
                                                                                                          arr2.pop(); // OK - don't affect arr1
                                                                                                          arr2[0].x = 'z'; // OK - don't affect arr1
                                                                                                          arr2[1][0] = 9; // OK - don't affect arr1

                                                                                                          console.log(arr1); // [ { x: 'a', y: 'b' }, [ 1, 2 ], [ 3, 4 ] ]
                                                                                                          console.log(arr2); // [ { x: 'z', y: 'b' }, [ 9, 2 ] ]








                                                                                                          share|improve this answer






























                                                                                                            2














                                                                                                            Quick Examples:




                                                                                                            1. If elements in the array are primitive types (string, number, etc.)





                                                                                                            var arr1 = ['a','b','c'];
                                                                                                            // arr1 and arr2 are independent and primitive elements are stored in
                                                                                                            // different places in the memory
                                                                                                            var arr2 = arr1.slice();
                                                                                                            arr2.push('d');
                                                                                                            console.log(arr1); // [ 'a', 'b', 'c' ]
                                                                                                            console.log(arr2); // [ 'a', 'b', 'c', 'd' ]






                                                                                                            1. If elements in the array are object literals, another array ({}, )





                                                                                                            var arr1 = [{ x: 'a', y: 'b'}, [1, 2], [3, 4]];
                                                                                                            // arr1 and arr2 are independent and reference's/addresses are stored in different
                                                                                                            // places in the memory. But those reference's/addresses points to some common place
                                                                                                            // in the memory.
                                                                                                            var arr2 = arr1.slice();
                                                                                                            arr2.pop(); // OK - don't affect arr1 bcos only the address in the arr2 is
                                                                                                            // deleted not the data pointed by that address
                                                                                                            arr2[0].x = 'z'; // not OK - affect arr1 bcos changes made in the common area
                                                                                                            // pointed by the addresses in both arr1 and arr2
                                                                                                            arr2[1][0] = 9; // not OK - same above reason

                                                                                                            console.log(arr1); // [ { x: 'z', y: 'b' }, [ 9, 2 ], [ 3, 4 ] ]
                                                                                                            console.log(arr2); // [ { x: 'z', y: 'b' }, [ 9, 2 ] ]







                                                                                                            1. Solution for 2: Deep Copy by element by element





                                                                                                            var arr1 = [{ x: 'a', y: 'b'}, [1, 2], [3, 4]];
                                                                                                            arr2 = JSON.parse(JSON.stringify(arr1));
                                                                                                            arr2.pop(); // OK - don't affect arr1
                                                                                                            arr2[0].x = 'z'; // OK - don't affect arr1
                                                                                                            arr2[1][0] = 9; // OK - don't affect arr1

                                                                                                            console.log(arr1); // [ { x: 'a', y: 'b' }, [ 1, 2 ], [ 3, 4 ] ]
                                                                                                            console.log(arr2); // [ { x: 'z', y: 'b' }, [ 9, 2 ] ]








                                                                                                            share|improve this answer




























                                                                                                              2












                                                                                                              2








                                                                                                              2







                                                                                                              Quick Examples:




                                                                                                              1. If elements in the array are primitive types (string, number, etc.)





                                                                                                              var arr1 = ['a','b','c'];
                                                                                                              // arr1 and arr2 are independent and primitive elements are stored in
                                                                                                              // different places in the memory
                                                                                                              var arr2 = arr1.slice();
                                                                                                              arr2.push('d');
                                                                                                              console.log(arr1); // [ 'a', 'b', 'c' ]
                                                                                                              console.log(arr2); // [ 'a', 'b', 'c', 'd' ]






                                                                                                              1. If elements in the array are object literals, another array ({}, )





                                                                                                              var arr1 = [{ x: 'a', y: 'b'}, [1, 2], [3, 4]];
                                                                                                              // arr1 and arr2 are independent and reference's/addresses are stored in different
                                                                                                              // places in the memory. But those reference's/addresses points to some common place
                                                                                                              // in the memory.
                                                                                                              var arr2 = arr1.slice();
                                                                                                              arr2.pop(); // OK - don't affect arr1 bcos only the address in the arr2 is
                                                                                                              // deleted not the data pointed by that address
                                                                                                              arr2[0].x = 'z'; // not OK - affect arr1 bcos changes made in the common area
                                                                                                              // pointed by the addresses in both arr1 and arr2
                                                                                                              arr2[1][0] = 9; // not OK - same above reason

                                                                                                              console.log(arr1); // [ { x: 'z', y: 'b' }, [ 9, 2 ], [ 3, 4 ] ]
                                                                                                              console.log(arr2); // [ { x: 'z', y: 'b' }, [ 9, 2 ] ]







                                                                                                              1. Solution for 2: Deep Copy by element by element





                                                                                                              var arr1 = [{ x: 'a', y: 'b'}, [1, 2], [3, 4]];
                                                                                                              arr2 = JSON.parse(JSON.stringify(arr1));
                                                                                                              arr2.pop(); // OK - don't affect arr1
                                                                                                              arr2[0].x = 'z'; // OK - don't affect arr1
                                                                                                              arr2[1][0] = 9; // OK - don't affect arr1

                                                                                                              console.log(arr1); // [ { x: 'a', y: 'b' }, [ 1, 2 ], [ 3, 4 ] ]
                                                                                                              console.log(arr2); // [ { x: 'z', y: 'b' }, [ 9, 2 ] ]








                                                                                                              share|improve this answer















                                                                                                              Quick Examples:




                                                                                                              1. If elements in the array are primitive types (string, number, etc.)





                                                                                                              var arr1 = ['a','b','c'];
                                                                                                              // arr1 and arr2 are independent and primitive elements are stored in
                                                                                                              // different places in the memory
                                                                                                              var arr2 = arr1.slice();
                                                                                                              arr2.push('d');
                                                                                                              console.log(arr1); // [ 'a', 'b', 'c' ]
                                                                                                              console.log(arr2); // [ 'a', 'b', 'c', 'd' ]






                                                                                                              1. If elements in the array are object literals, another array ({}, )





                                                                                                              var arr1 = [{ x: 'a', y: 'b'}, [1, 2], [3, 4]];
                                                                                                              // arr1 and arr2 are independent and reference's/addresses are stored in different
                                                                                                              // places in the memory. But those reference's/addresses points to some common place
                                                                                                              // in the memory.
                                                                                                              var arr2 = arr1.slice();
                                                                                                              arr2.pop(); // OK - don't affect arr1 bcos only the address in the arr2 is
                                                                                                              // deleted not the data pointed by that address
                                                                                                              arr2[0].x = 'z'; // not OK - affect arr1 bcos changes made in the common area
                                                                                                              // pointed by the addresses in both arr1 and arr2
                                                                                                              arr2[1][0] = 9; // not OK - same above reason

                                                                                                              console.log(arr1); // [ { x: 'z', y: 'b' }, [ 9, 2 ], [ 3, 4 ] ]
                                                                                                              console.log(arr2); // [ { x: 'z', y: 'b' }, [ 9, 2 ] ]







                                                                                                              1. Solution for 2: Deep Copy by element by element





                                                                                                              var arr1 = [{ x: 'a', y: 'b'}, [1, 2], [3, 4]];
                                                                                                              arr2 = JSON.parse(JSON.stringify(arr1));
                                                                                                              arr2.pop(); // OK - don't affect arr1
                                                                                                              arr2[0].x = 'z'; // OK - don't affect arr1
                                                                                                              arr2[1][0] = 9; // OK - don't affect arr1

                                                                                                              console.log(arr1); // [ { x: 'a', y: 'b' }, [ 1, 2 ], [ 3, 4 ] ]
                                                                                                              console.log(arr2); // [ { x: 'z', y: 'b' }, [ 9, 2 ] ]








                                                                                                              var arr1 = ['a','b','c'];
                                                                                                              // arr1 and arr2 are independent and primitive elements are stored in
                                                                                                              // different places in the memory
                                                                                                              var arr2 = arr1.slice();
                                                                                                              arr2.push('d');
                                                                                                              console.log(arr1); // [ 'a', 'b', 'c' ]
                                                                                                              console.log(arr2); // [ 'a', 'b', 'c', 'd' ]





                                                                                                              var arr1 = ['a','b','c'];
                                                                                                              // arr1 and arr2 are independent and primitive elements are stored in
                                                                                                              // different places in the memory
                                                                                                              var arr2 = arr1.slice();
                                                                                                              arr2.push('d');
                                                                                                              console.log(arr1); // [ 'a', 'b', 'c' ]
                                                                                                              console.log(arr2); // [ 'a', 'b', 'c', 'd' ]





                                                                                                              var arr1 = [{ x: 'a', y: 'b'}, [1, 2], [3, 4]];
                                                                                                              // arr1 and arr2 are independent and reference's/addresses are stored in different
                                                                                                              // places in the memory. But those reference's/addresses points to some common place
                                                                                                              // in the memory.
                                                                                                              var arr2 = arr1.slice();
                                                                                                              arr2.pop(); // OK - don't affect arr1 bcos only the address in the arr2 is
                                                                                                              // deleted not the data pointed by that address
                                                                                                              arr2[0].x = 'z'; // not OK - affect arr1 bcos changes made in the common area
                                                                                                              // pointed by the addresses in both arr1 and arr2
                                                                                                              arr2[1][0] = 9; // not OK - same above reason

                                                                                                              console.log(arr1); // [ { x: 'z', y: 'b' }, [ 9, 2 ], [ 3, 4 ] ]
                                                                                                              console.log(arr2); // [ { x: 'z', y: 'b' }, [ 9, 2 ] ]





                                                                                                              var arr1 = [{ x: 'a', y: 'b'}, [1, 2], [3, 4]];
                                                                                                              // arr1 and arr2 are independent and reference's/addresses are stored in different
                                                                                                              // places in the memory. But those reference's/addresses points to some common place
                                                                                                              // in the memory.
                                                                                                              var arr2 = arr1.slice();
                                                                                                              arr2.pop(); // OK - don't affect arr1 bcos only the address in the arr2 is
                                                                                                              // deleted not the data pointed by that address
                                                                                                              arr2[0].x = 'z'; // not OK - affect arr1 bcos changes made in the common area
                                                                                                              // pointed by the addresses in both arr1 and arr2
                                                                                                              arr2[1][0] = 9; // not OK - same above reason

                                                                                                              console.log(arr1); // [ { x: 'z', y: 'b' }, [ 9, 2 ], [ 3, 4 ] ]
                                                                                                              console.log(arr2); // [ { x: 'z', y: 'b' }, [ 9, 2 ] ]





                                                                                                              var arr1 = [{ x: 'a', y: 'b'}, [1, 2], [3, 4]];
                                                                                                              arr2 = JSON.parse(JSON.stringify(arr1));
                                                                                                              arr2.pop(); // OK - don't affect arr1
                                                                                                              arr2[0].x = 'z'; // OK - don't affect arr1
                                                                                                              arr2[1][0] = 9; // OK - don't affect arr1

                                                                                                              console.log(arr1); // [ { x: 'a', y: 'b' }, [ 1, 2 ], [ 3, 4 ] ]
                                                                                                              console.log(arr2); // [ { x: 'z', y: 'b' }, [ 9, 2 ] ]





                                                                                                              var arr1 = [{ x: 'a', y: 'b'}, [1, 2], [3, 4]];
                                                                                                              arr2 = JSON.parse(JSON.stringify(arr1));
                                                                                                              arr2.pop(); // OK - don't affect arr1
                                                                                                              arr2[0].x = 'z'; // OK - don't affect arr1
                                                                                                              arr2[1][0] = 9; // OK - don't affect arr1

                                                                                                              console.log(arr1); // [ { x: 'a', y: 'b' }, [ 1, 2 ], [ 3, 4 ] ]
                                                                                                              console.log(arr2); // [ { x: 'z', y: 'b' }, [ 9, 2 ] ]






                                                                                                              share|improve this answer














                                                                                                              share|improve this answer



                                                                                                              share|improve this answer








                                                                                                              edited Sep 11 '18 at 13:47

























                                                                                                              answered Sep 11 '18 at 13:41









                                                                                                              SridharKrithaSridharKritha

                                                                                                              2,5622226




                                                                                                              2,5622226























                                                                                                                  2














                                                                                                                  If your array contains elements of the primitive data type such as int, char, or string etc then you can user one of those methods which returns a copy of the original array such as .slice() or .map() or spread operator(thanks to ES6).



                                                                                                                  new_array = old_array.slice()


                                                                                                                  or



                                                                                                                  new_array = old_array.map((elem) => elem)


                                                                                                                  or



                                                                                                                  const new_array = new Array(...old_array);


                                                                                                                  BUT if your array contains complex elements such as objects(or arrays) or more nested objects, then, you will have to make sure that you are making a copy of all the elements from the top level to the last level else reference of the inner objects will be used and that means changing values in object_elements in new_array will still affect the old_array. You can call this method of copying at each level as making a DEEP COPY
                                                                                                                  of the old_array.



                                                                                                                  For deep copying, you can use the above-mentioned methods for primitive data types at each level depending upon the type of data or you can use this costly method(mentioned below) for making a deep copy without doing much work.



                                                                                                                  var new_array = JSON.parse(JSON.stringify(old_array));


                                                                                                                  There are a lot of other methods out there which you can use depending on your requirements. I have mentioned only some of those for giving a general idea of what happens when we try to copy an array into the other by value.






                                                                                                                  share|improve this answer




























                                                                                                                    2














                                                                                                                    If your array contains elements of the primitive data type such as int, char, or string etc then you can user one of those methods which returns a copy of the original array such as .slice() or .map() or spread operator(thanks to ES6).



                                                                                                                    new_array = old_array.slice()


                                                                                                                    or



                                                                                                                    new_array = old_array.map((elem) => elem)


                                                                                                                    or



                                                                                                                    const new_array = new Array(...old_array);


                                                                                                                    BUT if your array contains complex elements such as objects(or arrays) or more nested objects, then, you will have to make sure that you are making a copy of all the elements from the top level to the last level else reference of the inner objects will be used and that means changing values in object_elements in new_array will still affect the old_array. You can call this method of copying at each level as making a DEEP COPY
                                                                                                                    of the old_array.



                                                                                                                    For deep copying, you can use the above-mentioned methods for primitive data types at each level depending upon the type of data or you can use this costly method(mentioned below) for making a deep copy without doing much work.



                                                                                                                    var new_array = JSON.parse(JSON.stringify(old_array));


                                                                                                                    There are a lot of other methods out there which you can use depending on your requirements. I have mentioned only some of those for giving a general idea of what happens when we try to copy an array into the other by value.






                                                                                                                    share|improve this answer


























                                                                                                                      2












                                                                                                                      2








                                                                                                                      2







                                                                                                                      If your array contains elements of the primitive data type such as int, char, or string etc then you can user one of those methods which returns a copy of the original array such as .slice() or .map() or spread operator(thanks to ES6).



                                                                                                                      new_array = old_array.slice()


                                                                                                                      or



                                                                                                                      new_array = old_array.map((elem) => elem)


                                                                                                                      or



                                                                                                                      const new_array = new Array(...old_array);


                                                                                                                      BUT if your array contains complex elements such as objects(or arrays) or more nested objects, then, you will have to make sure that you are making a copy of all the elements from the top level to the last level else reference of the inner objects will be used and that means changing values in object_elements in new_array will still affect the old_array. You can call this method of copying at each level as making a DEEP COPY
                                                                                                                      of the old_array.



                                                                                                                      For deep copying, you can use the above-mentioned methods for primitive data types at each level depending upon the type of data or you can use this costly method(mentioned below) for making a deep copy without doing much work.



                                                                                                                      var new_array = JSON.parse(JSON.stringify(old_array));


                                                                                                                      There are a lot of other methods out there which you can use depending on your requirements. I have mentioned only some of those for giving a general idea of what happens when we try to copy an array into the other by value.






                                                                                                                      share|improve this answer













                                                                                                                      If your array contains elements of the primitive data type such as int, char, or string etc then you can user one of those methods which returns a copy of the original array such as .slice() or .map() or spread operator(thanks to ES6).



                                                                                                                      new_array = old_array.slice()


                                                                                                                      or



                                                                                                                      new_array = old_array.map((elem) => elem)


                                                                                                                      or



                                                                                                                      const new_array = new Array(...old_array);


                                                                                                                      BUT if your array contains complex elements such as objects(or arrays) or more nested objects, then, you will have to make sure that you are making a copy of all the elements from the top level to the last level else reference of the inner objects will be used and that means changing values in object_elements in new_array will still affect the old_array. You can call this method of copying at each level as making a DEEP COPY
                                                                                                                      of the old_array.



                                                                                                                      For deep copying, you can use the above-mentioned methods for primitive data types at each level depending upon the type of data or you can use this costly method(mentioned below) for making a deep copy without doing much work.



                                                                                                                      var new_array = JSON.parse(JSON.stringify(old_array));


                                                                                                                      There are a lot of other methods out there which you can use depending on your requirements. I have mentioned only some of those for giving a general idea of what happens when we try to copy an array into the other by value.







                                                                                                                      share|improve this answer












                                                                                                                      share|improve this answer



                                                                                                                      share|improve this answer










                                                                                                                      answered Sep 26 '18 at 13:52









                                                                                                                      Abhinav1602Abhinav1602

                                                                                                                      29949




                                                                                                                      29949























                                                                                                                          1














                                                                                                                          Here's a variant:



                                                                                                                          var arr1=['a', 'b', 'c'];
                                                                                                                          var arr2=eval(arr1.toSource());
                                                                                                                          arr2.push('d');
                                                                                                                          console.log('arr1: '+arr1+'narr2: '+arr2);
                                                                                                                          /*
                                                                                                                          * arr1: a,b,c
                                                                                                                          * arr2: a,b,c,d
                                                                                                                          */





                                                                                                                          share|improve this answer
























                                                                                                                          • not such a bad idea, though I'd better use JSON stringify/parse instead of eval, and yet another jsPerf compare would be good to check out, also note toSource is not standard and will not work in Chrome for example.

                                                                                                                            – dmi3y
                                                                                                                            Mar 24 '14 at 19:23
















                                                                                                                          1














                                                                                                                          Here's a variant:



                                                                                                                          var arr1=['a', 'b', 'c'];
                                                                                                                          var arr2=eval(arr1.toSource());
                                                                                                                          arr2.push('d');
                                                                                                                          console.log('arr1: '+arr1+'narr2: '+arr2);
                                                                                                                          /*
                                                                                                                          * arr1: a,b,c
                                                                                                                          * arr2: a,b,c,d
                                                                                                                          */





                                                                                                                          share|improve this answer
























                                                                                                                          • not such a bad idea, though I'd better use JSON stringify/parse instead of eval, and yet another jsPerf compare would be good to check out, also note toSource is not standard and will not work in Chrome for example.

                                                                                                                            – dmi3y
                                                                                                                            Mar 24 '14 at 19:23














                                                                                                                          1












                                                                                                                          1








                                                                                                                          1







                                                                                                                          Here's a variant:



                                                                                                                          var arr1=['a', 'b', 'c'];
                                                                                                                          var arr2=eval(arr1.toSource());
                                                                                                                          arr2.push('d');
                                                                                                                          console.log('arr1: '+arr1+'narr2: '+arr2);
                                                                                                                          /*
                                                                                                                          * arr1: a,b,c
                                                                                                                          * arr2: a,b,c,d
                                                                                                                          */





                                                                                                                          share|improve this answer













                                                                                                                          Here's a variant:



                                                                                                                          var arr1=['a', 'b', 'c'];
                                                                                                                          var arr2=eval(arr1.toSource());
                                                                                                                          arr2.push('d');
                                                                                                                          console.log('arr1: '+arr1+'narr2: '+arr2);
                                                                                                                          /*
                                                                                                                          * arr1: a,b,c
                                                                                                                          * arr2: a,b,c,d
                                                                                                                          */






                                                                                                                          share|improve this answer












                                                                                                                          share|improve this answer



                                                                                                                          share|improve this answer










                                                                                                                          answered Oct 6 '13 at 6:36









                                                                                                                          ZyoxZyox

                                                                                                                          286




                                                                                                                          286













                                                                                                                          • not such a bad idea, though I'd better use JSON stringify/parse instead of eval, and yet another jsPerf compare would be good to check out, also note toSource is not standard and will not work in Chrome for example.

                                                                                                                            – dmi3y
                                                                                                                            Mar 24 '14 at 19:23



















                                                                                                                          • not such a bad idea, though I'd better use JSON stringify/parse instead of eval, and yet another jsPerf compare would be good to check out, also note toSource is not standard and will not work in Chrome for example.

                                                                                                                            – dmi3y
                                                                                                                            Mar 24 '14 at 19:23

















                                                                                                                          not such a bad idea, though I'd better use JSON stringify/parse instead of eval, and yet another jsPerf compare would be good to check out, also note toSource is not standard and will not work in Chrome for example.

                                                                                                                          – dmi3y
                                                                                                                          Mar 24 '14 at 19:23





                                                                                                                          not such a bad idea, though I'd better use JSON stringify/parse instead of eval, and yet another jsPerf compare would be good to check out, also note toSource is not standard and will not work in Chrome for example.

                                                                                                                          – dmi3y
                                                                                                                          Mar 24 '14 at 19:23











                                                                                                                          1














                                                                                                                          There's the newly introduced Array.from, but unfortunately, as of the time of this writing it's only supported on recent Firefox versions (32 and higher). It can be simply used as follows:



                                                                                                                          var arr1 = [1, 2, 3];
                                                                                                                          console.log(Array.from(arr1)); // Logs: [1, 2, 3]


                                                                                                                          Reference: Here



                                                                                                                          Or Array.prototype.map may be used with an identity function:



                                                                                                                          function identity(param)
                                                                                                                          {
                                                                                                                          return param;
                                                                                                                          }

                                                                                                                          var arr1 = [1, 2, 3],
                                                                                                                          clone = arr1.map(identity);


                                                                                                                          Reference: Here






                                                                                                                          share|improve this answer


























                                                                                                                          • +1 for mentioning Array.from, which is now supported on all major browsers except Internet Explorer (source). .

                                                                                                                            – mgthomas99
                                                                                                                            Oct 18 '17 at 11:16


















                                                                                                                          1














                                                                                                                          There's the newly introduced Array.from, but unfortunately, as of the time of this writing it's only supported on recent Firefox versions (32 and higher). It can be simply used as follows:



                                                                                                                          var arr1 = [1, 2, 3];
                                                                                                                          console.log(Array.from(arr1)); // Logs: [1, 2, 3]


                                                                                                                          Reference: Here



                                                                                                                          Or Array.prototype.map may be used with an identity function:



                                                                                                                          function identity(param)
                                                                                                                          {
                                                                                                                          return param;
                                                                                                                          }

                                                                                                                          var arr1 = [1, 2, 3],
                                                                                                                          clone = arr1.map(identity);


                                                                                                                          Reference: Here






                                                                                                                          share|improve this answer


























                                                                                                                          • +1 for mentioning Array.from, which is now supported on all major browsers except Internet Explorer (source). .

                                                                                                                            – mgthomas99
                                                                                                                            Oct 18 '17 at 11:16
















                                                                                                                          1












                                                                                                                          1








                                                                                                                          1







                                                                                                                          There's the newly introduced Array.from, but unfortunately, as of the time of this writing it's only supported on recent Firefox versions (32 and higher). It can be simply used as follows:



                                                                                                                          var arr1 = [1, 2, 3];
                                                                                                                          console.log(Array.from(arr1)); // Logs: [1, 2, 3]


                                                                                                                          Reference: Here



                                                                                                                          Or Array.prototype.map may be used with an identity function:



                                                                                                                          function identity(param)
                                                                                                                          {
                                                                                                                          return param;
                                                                                                                          }

                                                                                                                          var arr1 = [1, 2, 3],
                                                                                                                          clone = arr1.map(identity);


                                                                                                                          Reference: Here






                                                                                                                          share|improve this answer















                                                                                                                          There's the newly introduced Array.from, but unfortunately, as of the time of this writing it's only supported on recent Firefox versions (32 and higher). It can be simply used as follows:



                                                                                                                          var arr1 = [1, 2, 3];
                                                                                                                          console.log(Array.from(arr1)); // Logs: [1, 2, 3]


                                                                                                                          Reference: Here



                                                                                                                          Or Array.prototype.map may be used with an identity function:



                                                                                                                          function identity(param)
                                                                                                                          {
                                                                                                                          return param;
                                                                                                                          }

                                                                                                                          var arr1 = [1, 2, 3],
                                                                                                                          clone = arr1.map(identity);


                                                                                                                          Reference: Here







                                                                                                                          share|improve this answer














                                                                                                                          share|improve this answer



                                                                                                                          share|improve this answer








                                                                                                                          edited Feb 6 '17 at 7:46









                                                                                                                          heena Jethva

                                                                                                                          554




                                                                                                                          554










                                                                                                                          answered Dec 10 '14 at 15:45









                                                                                                                          Ashraf SabryAshraf Sabry

                                                                                                                          1,68521924




                                                                                                                          1,68521924













                                                                                                                          • +1 for mentioning Array.from, which is now supported on all major browsers except Internet Explorer (source). .

                                                                                                                            – mgthomas99
                                                                                                                            Oct 18 '17 at 11:16





















                                                                                                                          • +1 for mentioning Array.from, which is now supported on all major browsers except Internet Explorer (source). .

                                                                                                                            – mgthomas99
                                                                                                                            Oct 18 '17 at 11:16



















                                                                                                                          +1 for mentioning Array.from, which is now supported on all major browsers except Internet Explorer (source). .

                                                                                                                          – mgthomas99
                                                                                                                          Oct 18 '17 at 11:16







                                                                                                                          +1 for mentioning Array.from, which is now supported on all major browsers except Internet Explorer (source). .

                                                                                                                          – mgthomas99
                                                                                                                          Oct 18 '17 at 11:16













                                                                                                                          1














                                                                                                                          You can do that in following way :
                                                                                                                          arr2 = arr1.map(x => Object.assign({}, x));






                                                                                                                          share|improve this answer




























                                                                                                                            1














                                                                                                                            You can do that in following way :
                                                                                                                            arr2 = arr1.map(x => Object.assign({}, x));






                                                                                                                            share|improve this answer


























                                                                                                                              1












                                                                                                                              1








                                                                                                                              1







                                                                                                                              You can do that in following way :
                                                                                                                              arr2 = arr1.map(x => Object.assign({}, x));






                                                                                                                              share|improve this answer













                                                                                                                              You can do that in following way :
                                                                                                                              arr2 = arr1.map(x => Object.assign({}, x));







                                                                                                                              share|improve this answer












                                                                                                                              share|improve this answer



                                                                                                                              share|improve this answer










                                                                                                                              answered May 31 '18 at 11:50









                                                                                                                              Harunur RashidHarunur Rashid

                                                                                                                              1,363713




                                                                                                                              1,363713























                                                                                                                                  1














                                                                                                                                  You could use ES6 with spread Opeartor, its simpler.



                                                                                                                                  arr2 = [...arr1];


                                                                                                                                  There are limitations..check docs Spread syntax @ mozilla






                                                                                                                                  share|improve this answer




























                                                                                                                                    1














                                                                                                                                    You could use ES6 with spread Opeartor, its simpler.



                                                                                                                                    arr2 = [...arr1];


                                                                                                                                    There are limitations..check docs Spread syntax @ mozilla






                                                                                                                                    share|improve this answer


























                                                                                                                                      1












                                                                                                                                      1








                                                                                                                                      1







                                                                                                                                      You could use ES6 with spread Opeartor, its simpler.



                                                                                                                                      arr2 = [...arr1];


                                                                                                                                      There are limitations..check docs Spread syntax @ mozilla






                                                                                                                                      share|improve this answer













                                                                                                                                      You could use ES6 with spread Opeartor, its simpler.



                                                                                                                                      arr2 = [...arr1];


                                                                                                                                      There are limitations..check docs Spread syntax @ mozilla







                                                                                                                                      share|improve this answer












                                                                                                                                      share|improve this answer



                                                                                                                                      share|improve this answer










                                                                                                                                      answered Jun 27 '18 at 9:06









                                                                                                                                      BluePieBluePie

                                                                                                                                      5116




                                                                                                                                      5116























                                                                                                                                          1














                                                                                                                                          Here is how you can do it for array of arrays of primitives of variable depth:



                                                                                                                                          // If a is array: 
                                                                                                                                          // then call cpArr(a) for each e;
                                                                                                                                          // else return a

                                                                                                                                          const cpArr = a => Array.isArray(a) && a.map(e => cpArr(e)) || a;

                                                                                                                                          let src = [[1,2,3], [4, ["five", "six", 7], true], 8, 9, false];
                                                                                                                                          let dst = cpArr(src);


                                                                                                                                          https://jsbin.com/xemazog/edit?js,console






                                                                                                                                          share|improve this answer






























                                                                                                                                            1














                                                                                                                                            Here is how you can do it for array of arrays of primitives of variable depth:



                                                                                                                                            // If a is array: 
                                                                                                                                            // then call cpArr(a) for each e;
                                                                                                                                            // else return a

                                                                                                                                            const cpArr = a => Array.isArray(a) && a.map(e => cpArr(e)) || a;

                                                                                                                                            let src = [[1,2,3], [4, ["five", "six", 7], true], 8, 9, false];
                                                                                                                                            let dst = cpArr(src);


                                                                                                                                            https://jsbin.com/xemazog/edit?js,console






                                                                                                                                            share|improve this answer




























                                                                                                                                              1












                                                                                                                                              1








                                                                                                                                              1







                                                                                                                                              Here is how you can do it for array of arrays of primitives of variable depth:



                                                                                                                                              // If a is array: 
                                                                                                                                              // then call cpArr(a) for each e;
                                                                                                                                              // else return a

                                                                                                                                              const cpArr = a => Array.isArray(a) && a.map(e => cpArr(e)) || a;

                                                                                                                                              let src = [[1,2,3], [4, ["five", "six", 7], true], 8, 9, false];
                                                                                                                                              let dst = cpArr(src);


                                                                                                                                              https://jsbin.com/xemazog/edit?js,console






                                                                                                                                              share|improve this answer















                                                                                                                                              Here is how you can do it for array of arrays of primitives of variable depth:



                                                                                                                                              // If a is array: 
                                                                                                                                              // then call cpArr(a) for each e;
                                                                                                                                              // else return a

                                                                                                                                              const cpArr = a => Array.isArray(a) && a.map(e => cpArr(e)) || a;

                                                                                                                                              let src = [[1,2,3], [4, ["five", "six", 7], true], 8, 9, false];
                                                                                                                                              let dst = cpArr(src);


                                                                                                                                              https://jsbin.com/xemazog/edit?js,console







                                                                                                                                              share|improve this answer














                                                                                                                                              share|improve this answer



                                                                                                                                              share|improve this answer








                                                                                                                                              edited Dec 13 '18 at 11:15

























                                                                                                                                              answered Dec 13 '18 at 11:10









                                                                                                                                              G.DenisG.Denis

                                                                                                                                              413




                                                                                                                                              413























                                                                                                                                                  1














                                                                                                                                                  let a = [1,2,3];


                                                                                                                                                  Now you can do any one of the following to make a copy of an array.



                                                                                                                                                  let b = Array.from(a); 


                                                                                                                                                  OR



                                                                                                                                                  let b = [...a];


                                                                                                                                                  OR



                                                                                                                                                  let b = new Array(...a); 


                                                                                                                                                  OR



                                                                                                                                                  let b = a.slice(); 


                                                                                                                                                  OR



                                                                                                                                                  let b = a.map(e => e);


                                                                                                                                                  Now, if i change a,



                                                                                                                                                  a.push(5); 


                                                                                                                                                  Then, a is [1,2,3,5] but b is still [1,2,3] as it has different reference.



                                                                                                                                                  But i think, in all the methods above Array.from is better and made mainly to copy an array.






                                                                                                                                                  share|improve this answer






























                                                                                                                                                    1














                                                                                                                                                    let a = [1,2,3];


                                                                                                                                                    Now you can do any one of the following to make a copy of an array.



                                                                                                                                                    let b = Array.from(a); 


                                                                                                                                                    OR



                                                                                                                                                    let b = [...a];


                                                                                                                                                    OR



                                                                                                                                                    let b = new Array(...a); 


                                                                                                                                                    OR



                                                                                                                                                    let b = a.slice(); 


                                                                                                                                                    OR



                                                                                                                                                    let b = a.map(e => e);


                                                                                                                                                    Now, if i change a,



                                                                                                                                                    a.push(5); 


                                                                                                                                                    Then, a is [1,2,3,5] but b is still [1,2,3] as it has different reference.



                                                                                                                                                    But i think, in all the methods above Array.from is better and made mainly to copy an array.






                                                                                                                                                    share|improve this answer




























                                                                                                                                                      1












                                                                                                                                                      1








                                                                                                                                                      1







                                                                                                                                                      let a = [1,2,3];


                                                                                                                                                      Now you can do any one of the following to make a copy of an array.



                                                                                                                                                      let b = Array.from(a); 


                                                                                                                                                      OR



                                                                                                                                                      let b = [...a];


                                                                                                                                                      OR



                                                                                                                                                      let b = new Array(...a); 


                                                                                                                                                      OR



                                                                                                                                                      let b = a.slice(); 


                                                                                                                                                      OR



                                                                                                                                                      let b = a.map(e => e);


                                                                                                                                                      Now, if i change a,



                                                                                                                                                      a.push(5); 


                                                                                                                                                      Then, a is [1,2,3,5] but b is still [1,2,3] as it has different reference.



                                                                                                                                                      But i think, in all the methods above Array.from is better and made mainly to copy an array.






                                                                                                                                                      share|improve this answer















                                                                                                                                                      let a = [1,2,3];


                                                                                                                                                      Now you can do any one of the following to make a copy of an array.



                                                                                                                                                      let b = Array.from(a); 


                                                                                                                                                      OR



                                                                                                                                                      let b = [...a];


                                                                                                                                                      OR



                                                                                                                                                      let b = new Array(...a); 


                                                                                                                                                      OR



                                                                                                                                                      let b = a.slice(); 


                                                                                                                                                      OR



                                                                                                                                                      let b = a.map(e => e);


                                                                                                                                                      Now, if i change a,



                                                                                                                                                      a.push(5); 


                                                                                                                                                      Then, a is [1,2,3,5] but b is still [1,2,3] as it has different reference.



                                                                                                                                                      But i think, in all the methods above Array.from is better and made mainly to copy an array.







                                                                                                                                                      share|improve this answer














                                                                                                                                                      share|improve this answer



                                                                                                                                                      share|improve this answer








                                                                                                                                                      edited Jan 2 at 18:03

























                                                                                                                                                      answered Nov 18 '18 at 6:43









                                                                                                                                                      Nitesh RanjanNitesh Ranjan

                                                                                                                                                      11916




                                                                                                                                                      11916























                                                                                                                                                          0














                                                                                                                                                          For ES6 array containing objects



                                                                                                                                                          cloneArray(arr) {
                                                                                                                                                          return arr.map(x => ({ ...x }));
                                                                                                                                                          }





                                                                                                                                                          share|improve this answer




























                                                                                                                                                            0














                                                                                                                                                            For ES6 array containing objects



                                                                                                                                                            cloneArray(arr) {
                                                                                                                                                            return arr.map(x => ({ ...x }));
                                                                                                                                                            }





                                                                                                                                                            share|improve this answer


























                                                                                                                                                              0












                                                                                                                                                              0








                                                                                                                                                              0







                                                                                                                                                              For ES6 array containing objects



                                                                                                                                                              cloneArray(arr) {
                                                                                                                                                              return arr.map(x => ({ ...x }));
                                                                                                                                                              }





                                                                                                                                                              share|improve this answer













                                                                                                                                                              For ES6 array containing objects



                                                                                                                                                              cloneArray(arr) {
                                                                                                                                                              return arr.map(x => ({ ...x }));
                                                                                                                                                              }






                                                                                                                                                              share|improve this answer












                                                                                                                                                              share|improve this answer



                                                                                                                                                              share|improve this answer










                                                                                                                                                              answered May 4 '18 at 19:09









                                                                                                                                                              askilondzaskilondz

                                                                                                                                                              2,55122034




                                                                                                                                                              2,55122034






















                                                                                                                                                                  1 2
                                                                                                                                                                  next




                                                                                                                                                                  protected by Tushar Gupta Jul 30 '14 at 12:24



                                                                                                                                                                  Thank you for your interest in this question.
                                                                                                                                                                  Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).



                                                                                                                                                                  Would you like to answer one of these unanswered questions instead?



                                                                                                                                                                  Popular posts from this blog

                                                                                                                                                                  MongoDB - Not Authorized To Execute Command

                                                                                                                                                                  How to fix TextFormField cause rebuild widget in Flutter

                                                                                                                                                                  in spring boot 2.1 many test slices are not allowed anymore due to multiple @BootstrapWith