Clone and clone deep an array in Javascript

The first, we will talk about the way to clone an array in Javascript, consider the example below:

 const ducks = ['1', '2', '3'];
 const ducks2 = ducks;

 // Do something with new array
 console.log(ducks2); // result: ['1', '2', '3']

 ducks2[0] = '4';

 console.log(ducks2); // result: ['4', '2', '3']
 console.log(ducks); // result: ['4', '2', '3']

Copy this code

In the example, we can't copy an array when we only use "=" because the arrays in JS are reference values, so when you try to copy it using the "=" it will only copy the reference to the original array and not the value of the array. So, what now?

Don't worry, there are three ways to duplicate an array in Javascript:

 const ducks = ['1', '2', '3'];

 // the first way with "slice" method
 const ducks2 = ducks.slice();

 // the second way with assign method from ES6
 const ducks2 = [...ducks];

 // the third way with "from" method of ES6
 const ducks2 = Array.from(ducks);

 // Do something with new array
 console.log(ducks2); // result: ['1', '2', '3']
 ducks2[0] = 4;
 console.log(ducks2); // result: ['4', '2', '3']
 console.log(ducks); // result: ['1', '2', '3']
Copy this code

And now, you can do anything with new array that it doesn't affect the original array's values

So, what is clone deep an array? what's different between clone and clone deep an array in Javascript? You can got it with the example below:

 const nestedDucks = [1, [1, 2], 3];
 const nestedDucksCopy = [...nestedDucks]; 

 // Do something with new array
 nestedDucksCopy[0] = 'x'; // change shallow element
 nestedDucksCopy[1][0] = 'y'; // change nested element

 console.log(nestedDucksCopy); // [ 'x', ['y', 2], 3 ]
 console.log(nestedDucks); // [ 1, ['y', 2], 3 ]
Copy this code

You can see that the origin array will be affected when we change the values nested element of the copied array. So what happen? That happened because when we clone an array, we just shallow copy only, we can't copy the deep element inside an array (That is what different between clone and clone deep) And now, we need to use one of two ways below to clone deep an array:

 const nestedDucks = [1, [1, 2], 3];

 // The first way, use the JSON's methods
 const nestedDucksCopy = JSON.parse(JSON.stringify(nestedArray)); 

 // The second way, import cloneDeep from 'lodash.clonedeep';
 const nestedDucksCopy = cloneDeep(nestedArray); 

 // Do something with new array
 nestedDucksCopy[0] = 'x'; // change shallow element
 nestedDucksCopy[1][0] = 'y'; // change nested element

 console.log(nestedDucksCopy); // [ 'x', ['y', 2], 3 ]
 console.log(nestedDucks); // [ 1, [1, 2], 3 ]
Copy this code


But, you need to note when you choice a method for each case:

- JSON.stringify/parse only work with Number and String and Object literal without function or Symbol properties.
- deepClone work with all types, function and Symbol are copied by reference.

© 2019 4codev

Created with love by Sil.