Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

151
Views
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

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.

about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!