Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 594
Himmel Avatar asked May 06 '16 03:05

Himmel


2 Answers

An easier way would be to use the array filter function

case REMOVE:
  return list.filter((item) => item.name !== n)
like image 135
Steffen Avatar answered Nov 02 '22 12:11

Steffen


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)
  ]
like image 6
QoP Avatar answered Nov 02 '22 11:11

QoP