How do I create a deep copy of an array in JavaScript?
Richard W
richard w profile pic

Creating a deep copy of an array in JavaScript involves copying not only the array itself but also all nested objects and arrays within it. Here's a step-by-step approach to achieving a deep copy: 1. Using the JSON methods: - You can create a deep copy of an array by converting it to a JSON string and then parsing it back into a new array. This method works well for arrays that only contain serializable data types such as numbers, strings, booleans, objects, and arrays.

1
2
3
4

   const originalArray = [1, 2, { a: 3 }, [4, 5]];
   const deepCopyArray = JSON.parse(JSON.stringify(originalArray));
   

In this example,JSON.stringify() converts the original arrayoriginalArray to a JSON string, andJSON.parse() parses the JSON string back into a new arraydeepCopyArray. Note that this method has limitations: - It cannot handle functions or symbols present in the original array, as they are not valid JSON data types. - It cannot handle circular references within objects or arrays, as JSON.stringify() throws an error in such cases. 2. Using recursion and iteration: - To handle arrays with non-serializable data types or circular references, you can create a custom deep copy function using recursion and iteration. This method allows for more control and customization but requires more complex implementation.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

   function deepCopyArray(originalArray) {
     const copiedArray = [];

     for (let i = 0; i < originalArray.length; i++) {
       const currentItem = originalArray[i];
       let copiedItem;

       if (Array.isArray(currentItem)) {
         copiedItem = deepCopyArray(currentItem); // Recursively copy nested arrays
       } else if (typeof currentItem === 'object' && currentItem !== null) {
         copiedItem = deepCopyObject(currentItem); // Recursively copy nested objects
       } else {
         copiedItem = currentItem; // Primitive values are copied as is
       }

       copiedArray.push(copiedItem);
     }

     return copiedArray;
   }
   

In this example, thedeepCopyArray() function recursively iterates over each item in the original array. If the current item is an array, it calls thedeepCopyArray() function recursively to create a deep copy of the nested array. If the current item is an object, it calls a separatedeepCopyObject() function to create a deep copy of the nested object. If the current item is a primitive value, it is directly copied. ThedeepCopyObject() function follows a similar recursive approach to handle nested objects. Note that this implementation assumes that the array does not contain functions or symbols, as they cannot be deep copied. If your use case involves such non-serializable data types, you will need to adjust the implementation accordingly. 3. Using external libraries: - There are external libraries like Lodash or Underscore.js that provide utility functions, including deep copying of arrays and objects. These libraries often offer optimized and comprehensive solutions for deep copying, handling complex scenarios efficiently.

1
2
3

   const deepCopyArray = _.cloneDeep(originalArray); // Using Lodash
   

In this example,_.cloneDeep() from Lodash is used to create a deep copy of the original arrayoriginalArray. When using external libraries, make sure to include the library in your project and follow their documentation for the specific deep copy functions they provide. Choose the method that best suits your requirements. The JSON method (JSON.parse(JSON.stringify())) is suitable for simple cases, while the recursion and iteration approach provides more flexibility. External libraries like Lodash or Underscore.js can be beneficial for more complex scenarios or when you require additional utility functions.