13

I'm trying to clone Array to a new one, and I want cloned array has no reference to original copy

I know there're splice and from method, but new array from those methods all has reference to original array

e.g.

let original = [ [1,2], [3,4] ];
let cloned = Array.from(original); // this will copy everything from original 
original[0][0] = -1;
console.log(cloned[0][0]); // the cloned array element value changes too

I also tried using loop to have cloned[i][j] = original[i][j], but result is the same

How can I create a new Array with every element having same value from original Array, but the cloned Array should have no reference to original Array?

thanks!

jerry
  • 1,196
  • 2
  • 9
  • 21

1 Answers1

20

By using this method we can create a copy of an array. Please check the below example. Credits to this SO Answer

let original = [
  [1, 2],
  [3, 4]
];
let cloned = JSON.parse(JSON.stringify(original)); // this will copy everything from original 
original[0][0] = -1;
console.log(cloned); // the cloned array element value changes too
console.log(original);
.as-console {
  height: 100%;
}

.as-console-wrapper {
  max-height: 100% !important;
  top: 0;
}
Naren Murali
  • 19,250
  • 3
  • 27
  • 54