Sachin
Sachin

Reputation: 155

Copy the original array to another array with out modifing original array?

I have two array and contain the data like

let arr1 = ['IND','JPN','USA']
let arr2 = [...arr1]
console.log(arr2)

I want to copy the data from arr1 to arr2 as I already copied using ... But here there is change in arr1 also change in arr2 ,How would I avoid items in arr2 won't change in case any changes into the arr1.

The arr1 data coming from the render and passing using props to another component .

Upvotes: 0

Views: 34

Answers (2)

Ignacio
Ignacio

Reputation: 1056

[...arr1] is doing a shallow copy, as long as the values you're cloning are just one level deep, then you're fine with [...arr1]. In your example updating arr1 won't change arr2

let arr1 = [1,2,3,4];
let arr2 = [...arr1];
// ex.  
// arr1[0] = 'A';  
// arr2 will still be [1,2,3,4]  

However for deep cloning. In case the items in your array would have objects.
you would need to use a different solution. Lodash has a method for this:

let arr2 = _.cloneDeep(arr1);

There's also a way to do deep cloning with JSON.stringify, but if you have functions assigned in one of your objects, those won't be cloned

JSON.parse(JSON.stringify(arrayOfObjects))

Upvotes: 3

rrd
rrd

Reputation: 5957

Have you tried Array.from()?

let arr2 = Array.from(arr1);

You can see the link at MDN

Upvotes: 0

Related Questions