0

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

pilchard
  • 12,414
  • 5
  • 11
  • 23

1 Answers1

1

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.

JSmart523
  • 2,069
  • 1
  • 7
  • 17