There are several easy ways to clone an array in JavaScript. You can use the Array#slice() method, or the 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 approaches are by concat()-ing the array to an empty array and by using 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

#javascript #developer #array

Copy an Array in JavaScript
1.70 GEEK