Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Creating an Array clone with spread operator, but it still has reference to original array

So I have these few lines of code:

  console.log(...cells);

  let testCells = [...cells];
  testCells[index].shape = selectedShape;
  testCells[index].player = player;

  console.log(...cells);

The interesting thing is that it is console.log()ing back the following.

enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I don’t quite get it, why does cells change? There is no other part of the code that could interfere with cells. Any tips?

Full code available here.

>Solution :

It looks like even though you’re spreading all the objects into the new array, it is still a reference to the old objects. You can break the reference by using JSON.stringify and JSON.parse to avoid any old unintended relationships.

  const cells = [
    {shape: 0, player: 0},
    {shape: 0, player: 0},
    {shape: 0, player: 0},
    {shape: 0, player: 0},
    {shape: 0, player: 0},
    {shape: 0, player: 0},
    {shape: 0, player: 0},
    {shape: 0, player: 0},
    {shape: 0, player: 0},
  ];
  
  console.log(...cells);
  
  const breakRef = obj => JSON.parse(JSON.stringify(obj));

  let testCells = breakRef(cells);
  testCells[0].shape = 1;
  testCells[0].player = 0;

  console.log(...cells);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading