How to clone an array in JavaScript?
JavaScript provides quite a few ways to clone an array, most of which are pretty similar in terms of performance and results. Here’s a quick rundown of some of the available options.
The spread operator
ES6 introduced the spread operator (…), which provides probably the easiest and most common way to create a shallow clone of an array.
let x = [1, 2, 3, 4];
let y = [...x];
console.log(y)
// Expected output: Array [1, 2, 3, 4]
Array.from()
Array.from() has a very powerful API that can be used for many different things, including creating a copy of an array.
console.log(Array.from('foo'));
// Expected output: Array ["f", "o", "o"]
Array.prototype.slice()
Similarly to the spread operator, Array.prototype.slice() can be used to create a shallow copy of an array.
const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];
console.log(animals.slice(2));
// Expected output: Array ["camel", "duck", "elephant"]
Array.prototype.map()
Looking into one of the more unorthodox options, Array.prototype.map() can be used to map each element of an array to itself to create a new array.
const array1 = [1, 4, 9, 16];
// Pass a function to map
const map1 = array1.map((x) => x * 2);
console.log(map1);
// Expected output: Array [2, 8, 18, 32]
Array.prototype.filter()
Similarly, Array.prototype.filter() can be used to return true for each and every element, resulting in a new array with all of the original array’s elements.
const words = ['spray', 'elite', 'exuberant', 'destruction', 'present'];
const result = words.filter((word) => word.length > 6);
console.log(result);
// Expected output: Array ["exuberant", "destruction", "present"]
Object.assign()
Finally, Object.assign() can be used in the exact same way as it’s used to create a clone of an object, but for an array instead.
let x = [1, 2, 3, 4];
let y = Object.assign([], x);
console.log(y);
// Expected output: Array [1, 2, 3, 4]
structuredClone()
If you’re looking to clone an array that contains objects, functions or class instances, you can use the structuredClone() global function, which can be used to deep clone objects.
const a = [{ foo: 'bar' }, { baz: 'qux' }];
const b = structuredClone(a);
console.log(b);
// Expected output: Array [Object { foo: "bar" }, Object { baz: "qux" }]