Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
166
rated 0 times [  170] [ 4]  / answers: 1 / hits: 17400  / 7 Years ago, fri, january 12, 2018, 12:00:00

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!


More From » javascript

 Answers
11

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




[#55481] Monday, January 8, 2018, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
longd

Total Points: 616
Total Questions: 110
Total Answers: 101

Location: Andorra
Member since Sat, May 27, 2023
1 Year ago
;