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!

1
  • 3
    Array.prototype.slice copies the array
    – Ilia Choly
    Commented Jan 12, 2018 at 4:21

1 Answer 1

21

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;
}

4
  • awesome! this is exactly what I need!
    – jerry
    Commented Jan 12, 2018 at 5:44
  • @jerry You're welcome! Commented Jan 12, 2018 at 5:46
  • This works smoothly!
    – Rddevelop
    Commented Feb 28, 2019 at 9:57
  • this solution worked like a charm, tried to slice method and did not make it work. Thank u.
    – Coder0997
    Commented Jun 10, 2020 at 16:34

Not the answer you're looking for? Browse other questions tagged or ask your own question.