0

Again a confusing Issue:

Here I copied the array into another variable and I expect not to change the original array when I change something in another one but both arrays change Why?

 const groups = [[1, 2, 3, 4 ,5], [2,3]];
 const sets = [...groups];
 
 sets[1].push(9000); // I just push a number into sets NOT groups
 
 console.log(sets);
 console.log(groups); 
 

This only happens if we have an array of arrays!

What I'm missing and How to fix this?

TheMaster
  • 45,448
  • 6
  • 62
  • 85
Sara Ree
  • 3,417
  • 12
  • 48
  • 1
    The spread syntax performs a shallow copy, not a _deep_ copy. The arrays inside of the copied array are still references to the same arrays that are in the `groups` arrays. – Nick Parsons Oct 02 '20 at 14:47
  • wait....what? so what should I do... – Sara Ree Oct 02 '20 at 14:48
  • if its just a 2d array, you could do something like `const sets = groups.map(arr => [...arr])`, this will clone each inner array, and will be stored in the resulting outer array produced by .map(). – Nick Parsons Oct 02 '20 at 14:52

1 Answers1

1

The spread operator does only shallow copy of groups. So the arrays are copied by reference and if you change those, the original arrays are affected.

Edit: if you need a deep clone, you may want to look here: Deep copy in ES6 using the spread syntax (JSON.stringify/JSON.parse should prevent another 3rd party library).

JeffRSon
  • 10,404
  • 4
  • 26
  • 51