-1

I'm trying to use Array.pop(Array.indexOf(value)) but it delete the last element in the index even if the value of that index is not same as I set it, can you please help me

  CheckBoxHandler1(e) {
    console.log(e.target.checked, e.target.name);
    let temp = [...this.state.boxes];
    e.target.checked === true
      ? temp.push(e.target.name)
      : temp.pop(temp.indexOf(e.target.name));
    this.setState({
      boxes: temp,
    });
}
Drsaud
  • 385
  • 2
  • 6
  • 15
  • 3
    [pop](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/pop) always removes the last element from an array. If you want to remove an element at a specific index i'd suggest looking at [How can I remove a specific item from an array?](https://stackoverflow.com/questions/5767325/how-can-i-remove-a-specific-item-from-an-array) – Reyno Oct 20 '21 at 06:42
  • It's not clear what you're trying to do. Is it something [different from your last question](https://stackoverflow.com/questions/69629816/array-splice-not-woking-when-there-is-one-index-left)? Can you produce a [mcve], perhaps, using some of that code. – Andy Oct 20 '21 at 06:43
  • @Reyno yes I thought If I specifed the index it will pop it , but thanks to Mr.Nicolas the solution is splice insted of pop – Drsaud Oct 20 '21 at 06:50
  • 1
    Hi @Andy, I used the code then I find some complicity specially when I want to use to do query in Elasticsearch (search engine) I thought that best approach for me to use this way, I really appreciate your help – Drsaud Oct 20 '21 at 06:52

1 Answers1

3

It happens because Array.prototype.pop() always remove the last element of the array.

If you want to remove one specific element, you need to do the following:

temp.splice(temp.indexOf(e.target.name), 1);