How to Deep Copy an Array in JavaScript?

Estimated read time 1 min read

There are several ways to perform a deep copy of an array in JavaScript, which is creating a new array with the same elements and nested arrays as the original array, but with different references.

Here’s an example implementation using the JSON.parse and JSON.stringify methods:

function deepCopy(arr) {
  return JSON.parse(JSON.stringify(arr));
}

You can use this function like this:

const original = [1, [2, [3, 4, [5]]], 6];
const copy = deepCopy(original);
console.log(copy); // [1, [2, [3, 4, [5]]], 6]

This method works well for arrays containing only primitive data types, such as numbers and strings, but it does not work for arrays containing functions, objects, or other complex data types. In these cases, a more manual approach may be required.

Here’s an example implementation using the Array.prototype.map method:

function deepCopy(arr) {
  return arr.map(function (item) {
    if (Array.isArray(item)) {
      return deepCopy(item);
    } else {
      return item;
    }
  });
}

This method can handle arrays containing complex data types, and you can use it in the same way as the previous example.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply