2

I have a simple array in React's state, consisting of only integers:

this.state = {
  myArray: [1,2,3]
}

I'm trying to replace a value in an immutable way (value 2 should be replaced by 8):

const valueToReplace = 2
const newValue = 8
const myArray = this.state.myArray
const arrayPosition = myArray.indexOf(valueToReplace)
const newArray = Object.assign([], myArray, {arrayPosition: newValue})

this.setState({myArray: newArray})

But my way doesn't change myArray in state. I think I'm not using Object.assign in the correct way.

2 Answers 2

2

You can use Array.prototype.slice to copy the array, mutate your copy, then assign it. Since you're creating a new array instead of modifying an existing one, you're still safe from mutation issues.

const valueToReplace = 2
const newValue = 8
const newArray = this.state.myArray.slice() // copy
const arrayPosition = newArray.indexOf(valueToReplace)
newArray[arrayPosition] = newValue

this.setState({myArray: newArray})
Sign up to request clarification or add additional context in comments.

Comments

1

It is better to create a clone of an array first and then replace the value:

const valueToReplace = 2
const newValue = 8
const myArray = this.state.myArray.slice(0);
const arrayPosition = myArray.indexOf(valueToReplace)
myArray[arrayPosition] = newValue

this.setState({myArray: newArray})

The Object.assign just clones and object/array into another var and is not changing the value within the array.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.