-1

how can I delete an array item if I know the index?

deleteItem = (index) => {
    setItems(prevState => prevState.filter((item) => item.index !== index));
}

item.index doesn´t exist. thank you!

also.. is this way faster than?

deleteItem = (index) => {
    setItems((prevState) => prevState.splice(index - 1, 1));
}
handsome
  • 1,778
  • 2
  • 25
  • 48
  • filter accepts extra parameters so change your filter callback to `.filter((item,idx) => idx !== index) ` – TommyBs Apr 22 '20 at 10:33
  • 2
    Pretty much every possible way to do this has been covered here: [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) – DBS Apr 22 '20 at 10:35

1 Answers1

0

The filter function can take a 2nd argument which is element index

deleteItem = (index) => {
    setItems(prevState => prevState.filter((item, i) => (i !== index)));
}
Mahdi N
  • 1,678
  • 2
  • 11
  • 26
  • is this the preferred way or prevState.splice(index - 1, 1) ? – handsome Apr 22 '20 at 10:35
  • Yes if it depends only on index splice is better. Check this https://stackoverflow.com/questions/44435141/remove-object-in-array-using-filter-and-splice-which-one-is-best-approach-in-ang – Mahdi N Apr 22 '20 at 10:39