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?
For ES6 array containing objects
Dan, no need to use fancy tricks. All you need to do is make copy of arr1 by doing this.
Now
arr1
andarr2
are two different array variables stored in separate stacks. Check this out on jsfiddle.Now you can do any one of the following to make a copy of an array.
OR
OR
OR
Now, if i change a,
Then, a is [1,2,3,5] but b is still [1,2,3] as it has difference reference.
But i think, in all the methods above Array.from is better and made mainly to copy an array.
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:
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
Here are few more way to copy:
If you are in an environment of ECMAScript 6, using the Spread Operator you could do it this way: