How to copy an array in JavaScript
There are several easy ways to clone an array in JavaScript. You can use Array#slice()
method or spread operator .
const arr = ['hello', 'world'];
// Clone using `slice()`
const arr2 = arr.slice();
arr2; // ['hello', 'world']
arr2 === arr; // false
// Clone using spread operator `...`
const arr3 = [...arr];
arr2; // ['hello', 'world']
arr2 === arr; // false
Two other common ways are concat()
- convert the array to an empty array and use the map()
method:
// Clone using `concat()`
const arr4 = [].concat(arr);
arr4; // ['hello', 'world']
arr4 === arr; // false
// Clone using `map()`
const arr5 = arr.map(v => v);
arr5; // ['hello', 'world']
arr5 === arr; // false
These 4 methods of copying an array are practically the same, and there is not much reason to prefer one over the other. The most notable difference is slice()
enjoying slightly better browser support – all the way up to Internet Explorer 4.
deep copy vs shallow copy
Remember that all 4 methods above create shallow . In other words, they clone the array itself, not array elements. It does this when you have an array of primitives (numbers, strings, null
, undefined
), but when you have an array of objects.
const arr = [{ answer: 42 }];
const arr2 = arr.slice();
arr2[0].answer = 0;
// `0`, because `arr[0]` is a reference to the same object as `arr2[0]`
arr[0].answer;
JavaScript doesn't have a built-in method for deep cloning of arrays. You need to use a cloneDeep()
function with , like lodash .
const arr = [{ answer: 42 }];
const arr2 = require('lodash').cloneDeep(arr);
arr2[0].answer = 0;
// `42`, because Lodash did a deep clone.
arr[0].answer;
0 Comments