Himmel Himmel - 4 days ago 5
React JSX Question

Redux reducer to remove an object from a list by name

Most of the examples I've seen regarding removing an item from a list use the index of the item in the list, for example:

case REMOVE:
return [
...list.slice(0, action.index)
...list.slice(action.index + 1)
]


But if I want to dispatch an action that doesn't have access to the index of an item in a list, but only the name, how can I filter through a set of objects and only remove an object with
n
name?

QoP QoP
Answer

You can use findIndex() method if you are using ES6+ in order to find the index.

case REMOVE:
  let index = list.findIndex((x) => x.name === n); 
  return [
    ...list.slice(0, index),
    ...list.slice(index + 1)
  ]
Comments