copy a deep array in javascript

To copy a deep array in JavaScript, you can use a combination of JSON.parse() and JSON.stringify(). Here's an example:

index.tsx
let originalArray = [[1, 2], [3, 4], [5, 6]];

// Deep copy the array
let newArray = JSON.parse(JSON.stringify(originalArray));

// Modifying the original array will not affect the copied array
originalArray[0][0] = 10;

console.log(originalArray); // [[10, 2], [3, 4], [5, 6]]
console.log(newArray); // [[1, 2], [3, 4], [5, 6]]
329 chars
11 lines

In this example, we use JSON.stringify() to convert the original array to a JSON string, and then JSON.parse() to parse that string back into a new array. This creates a new array with the same values as the original array, but they are stored in different memory locations. Therefore, modifying the original array will not affect the copied array, and vice versa.

related categories

gistlibby LogSnag