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

186
Views
Shouldn't using spread syntax not reference the original array?

I have an Object array in my state called names, i'm trying to make a copy of this array to another Object array in state called shuffledNames, but when i shuffle the shuffledNames using the code below, the original names changes the ids to match the new shuffled ids. See images below for an example. I've tryed using .concat(), .slice(). I do not know what to try anymore.

handleSort = () => {
  let tempName = [...this.state.names];

  let shuffledNames = tempName;

  for (let i = shuffledNames.length; i-- > 1; ) {
    let j = Math.floor(Math.random() * i);
    let temp = shuffledNames[i];
    shuffledNames[i] = shuffledNames[j];
    shuffledNames[j] = temp;
  }

  shuffledNames.forEach((shuffledName, index) => {
    shuffledName.id = index;
  });

  this.setState({ shuffledNames: shuffledNames });
};

This is my state before shuffling

This is my state before shuffling

This is my state after shuffling

This is my state after shuffling

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

The spread operator is a shallow clone, so it's a new array but the same values which are object references, not new objects. You need to find or code your own clone or deep copy function. Last one I used was randa's clone function but that was because someone else on my team had already imported that library.

about 4 years ago · Juan Pablo Isaza 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!