1

I have a fixed array(9) and I want to update the value of the array, this works perfectly but I want to optimize the code:

constructor (props) {
  super();
  this.state ={
    token: "X",
    val: ["","","","","","","","",""]
  };
}

intelligentComputerPlay () {
  this.setState({
    val: [
      this.state.token,
      this.state.val[1],
      this.state.val[2],
      this.state.val[3],
      this.state.val[4],
      this.state.val[5],  
      this.state.val[6],  
      this.state.val[7],  
      this.state.val[8]
    ];
  });

4
  • 1
    Could you expand on what is the general goal? This seems like a very wrong approach, but we cannot suggest anything better without knowing the general context. Commented Feb 10, 2018 at 22:14
  • By optimize, do you mean make cleaner? Commented Feb 10, 2018 at 22:14
  • @KamilSolecki in intelligentComputerPlay () method i just change the first value but i have written all the elements of the list, i need just updates the value that will be changing in the list. Is it possible? Commented Feb 10, 2018 at 22:43
  • @AustinBrunkhorst yes? Commented Feb 10, 2018 at 22:44

1 Answer 1

1

I think this could work.

this.setState(prevState => ({
     val: [token, ...prevState.val.slice(1, prevState.val.length - 1)]
}));
Sign up to request clarification or add additional context in comments.

2 Comments

how to write it if i want to change the third element for example?
val: [...prevState.val.slice(0, 3), token, ...prevState.val.slice(5, prevState.val.length - 1)]

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.