Sometimes, you need to work with an array while ensuring you don't modify the original. Instead of a clone
method, arrays have a slice
method that lets you perform a shallow copy of any part of an array. Keep in mind that this only clones the first level. This works well with primitive types, like numbers and strings, but not objects.
To shallow-clone an array (i.e. have a new array instance but with the same elements), you can use the following one-liner:
var clone = arrayToClone.slice();
This calls the built-in JavaScript Array.prototype.slice
method. If you pass arguments to slice
, you can get more complicated behaviors that create shallow clones of only part of an array, but for our purposes just calling slice()
will create a shallow copy of the entire array.
All method used to convert array like objects to array are applicable to clone an array:
arrayToClone = [1, 2, 3, 4, 5];
clone1 = Array.from(arrayToClone);
clone2 = Array.of(...arrayToClone);
clone3 = [...arrayToClone] // the shortest way
arrayToClone = [1, 2, 3, 4, 5];
clone1 = Array.prototype.slice.call(arrayToClone);
clone2 = [].slice.call(arrayToClone);