Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript - how to clone Array without reference [duplicate]

Tags:

javascript

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!

like image 679
jerry Avatar asked Jan 12 '18 04:01

jerry


People also ask

How do you copy an array without references?

To create a real copy of an array, you need to copy over the value of the array under a new value variable. That way this new array does not reference to the old array address in memory.

How do you copy an array without changing the original array?

To create the copy or clone of the array we can use the spread operator or splice method. Steps : Create the clone of the array using the spread operator or slice method.

How do you clone an array in JavaScript?

To duplicate an array, just return the element in your map call. numbers = [1, 2, 3]; numbersCopy = numbers. map((x) => x); If you'd like to be a bit more mathematical, (x) => x is called identity.

How will you remove duplicates from a JS array?

Use the filter() method: The filter() method creates a new array of elements that pass the condition we provide. It will include only those elements for which true is returned. We can remove duplicate values from the array by simply adjusting our condition.


1 Answers

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;
}
like image 93
Naren Murali Avatar answered Sep 16 '22 17:09

Naren Murali