How Not to Do it!
Your first instinct may be to do the following:
var pets = ['fish', 'parrot', 'cat']; var petsClone = pets;
THIS WILL NOT WORK!
petsClone will simply become a reference to the variable pets – not a copy. pets and petsClone won’t be copies of each other, they will both be names pointing to the same variable.
If one is updated, the other will change, which may not be the behaviour you want if you are copying an array.
Shallow cloning will only clone the values in the first level of the array. Any nested values will NOT be cloned, so watch out for this one if you’re working with multidimensional arrays! Shallow cloning is still useful for when you are working with two dimensional arrays and want to focus on performance and code simplicity.
Shallow Cloning Arrays Using ES6 Spread Syntax (…)
var pets = ['fish', 'parrot', 'cat']; var petsClone = [...pets];
The spread syntax expands the values within an array, so calling it inside a newly declared array will clone the contents of the other array into the new array.
Using JSON Functions to Deep Clone an Array
Below, a multidimensional or nested array is declared. The array pets contains two sub-arrays, each containing their own values. Attempt to use the spread syntax above will not clone the values in these sub arrays, they will be referenced.
You could write a complex loop to dive into each sub-array and clone the values, but there is a much better, if a little hacky solution – converting the original array to JSON, and then decoding it into a new array.
var pets = [['dog', 'cat'], ['fish', 'frog']]; var petsCopy = JSON.parse(JSON.stringify(pets));
Watch Out for Custom Classes/Objects
If you are deep cloning an array containing custom object classes, they will be converted to generic objects, and any references within them will be lost!
Whether or not this is a problem is entirely dependent on what you’re trying to accomplish. You may need to loop through the cloned array and use Object.assign() to ensure cloned objects are of the right class.
Test, Test, Test
If you’re building something mission critical, or which deals with money (like an online shop), and you are duplicating arrays, make sure you test your code and make sure your code is behaving in the way you intend it to!