Skip to content

JavaScript copy array without reference | Example code

  • by

Use JSON.parse() and JSON.stringify() methods to copy the array without reference in JavaScript. If these objects are simple objects, they can be serialized in JSON.

JSON.parse(JSON.stringify(mainArray));

JavaScript copy array without reference

In simple example code using this method, we can create a copy of an array. Please check the below example.

<!DOCTYPE html>
<html>
<body>

  <script>
    let original = [1,2,3,4,5];
    let cloned = JSON.parse(JSON.stringify(original)); 

    original[0] = -1;
    console.log(cloned); 
    console.log(original);

  </script>

</body>
</html> 

Output:

JavaScript copy array without reference

More examples 2d array

let original = [
  [1, 2],
  [3, 4]
];
let cloned = JSON.parse(JSON.stringify(original)); // copy everything from original 
original[0][0] = -1;

console.log(cloned); // the cloned array element value changes too
console.log(original);

Output:

[[1,2],[3,4]]
[[-1,2],[3,4]]

Copy array by value

Basically, the slice() operation clones the array and returns a reference to a new array. The slice() copies object references into the new array. Both the original and new arrays refer to the same object. If a referenced object changes, the changes are visible to both the new and original arrays.

let oldArray = [1, 2, 3, 4, 5];

let newArray = oldArray.slice();

console.log({newArray});

Output:{ "newArray": [ 1, 2, 3, 4, 5 ] }

Do comment if you have any doubts or suggestions on this 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