Shallow and deep copyShallow copy: only the original array object is cloned, the original content is referenced by the new array.
Deep copy: the objects inside the original array are cloned. Useful when you want to work on a copy of the original data.
A shallow copy simply creates a new array object with the same references to the objects of the original array.
If you update an object inside the cloned array, the original object will be updated.
How to create a shallow copy
Here some examples, other methods are available (loop etc.):
// spread operator const newArraySpread = [... originalArray]; // slice const newArraySlice = originalArray.slice(); // Array class const newArrayFrom = Array.from(originalArray)
According to some benchmarks,
splice should be the fastest method. You can test with your data in this online benchmark: https://jsben.ch/lO6C5
A deep copy clones the original array and his content to new objects.
There are no references with the original array. You can modify the content without an impact on the original data.
How to create a deep copy
const newArray = JSON.parse(JSON.stringify(originalArray));
This method is the easiest because it avoids a custom implementation, but it can have issues with circular references and big arrays (performance).