Skip to content

JavaScript deep copy array

  • by

There are several methods to create a deep copy of an array in JavaScript, such as the spread operator, Array.from(), or JSON.parse() and JSON.stringify().

A deep copy of an array in JavaScript creates a new array with its own memory reference and copies all the elements from the original array. Modifying an element in the new array or the original array will not affect the other array.

JavaScript deep copy array example

A simple example code creates a deep copy of an array in JavaScript, you can use one of the following methods:

Spread operator:

The spread operator can be used to create a new array with the same elements as the original array.

const originalArray = [1, 2, 3];
const copyArray = [...originalArray];

console.log(originalArray); // [1, 2, 3]
console.log(copyArray); // [1, 2, 3]

// Modify original array
originalArray[0] = 4;

console.log(originalArray); // [4, 2, 3]
console.log(copyArray); // [1, 2, 3] (unchanged)

Array.from() method:

The Array.from() method creates a new, shallow-copied array from an array-like or iterable object.

const originalArray = [1, 2, 3];
const copyArray = Array.from(originalArray);

console.log(originalArray); // [1, 2, 3]
console.log(copyArray); // [1, 2, 3]

// Modify original array
originalArray[0] = 4;

console.log(originalArray); // [4, 2, 3]
console.log(copyArray); // [1, 2, 3] (unchanged)

JSON.parse() and JSON.stringify() methods:

The JSON.stringify() method converts a JavaScript value to a JSON string and the JSON.parse() method parses a JSON string and returns a JavaScript value.

const originalArray = [1, 2, 3];
const copyArray = JSON.parse(JSON.stringify(originalArray));

console.log(originalArray); // [1, 2, 3]
console.log(copyArray); // [1, 2, 3]

// Modify original array
originalArray[0] = 4;

console.log(originalArray); // [4, 2, 3]
console.log(copyArray); // [1, 2, 3] (unchanged)

Output:

JavaScript deep copy array

In JavaScript, when you copy an array using the assignment operator (=) or the slice() method, you create a shallow copy of the array. This means that the new array and the original array share the same memory reference, so if you modify an element in the new array or the original array, the change is reflected in both arrays.

A deep copy, on the other hand, creates a new array with its own memory reference, and all the elements in the new array are copies of the elements in the original array. If you modify an element in the new array or the original array, the change is not reflected in the other array.

Comment if you have any doubts or suggestions on this Js Array topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading