14

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 Commented Jan 12, 2018 at 4:21

1 Answer 1

24

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

Sign up to request clarification or add additional context in comments.

2 Comments

awesome! this is exactly what I need!
This works smoothly!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.