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];
slice
andsplice
operations and new spread operator andArray.from
have much slower implementation. Look at perfjs.fnfo – Lamiavar 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. – Chansonlet arr2 = [...arr1];
developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… – Incandescencea = b;
you actually tell the program to point in both cases to a same symbolic link in random access memory. And when a value at this symbolic link is changed it affectsa
andb
... So if you use a spread operatora= [...b];
program will create an additional symbolic link to a different location in random access memory and you can then manipulatea
andb
independently. – Inveterate