1

React redux succinct way to remove object from array if match certain criteria and without mutating array

I have an array that contains a number of objects.

I am wondering what is the cleanest way to remove the items from the array if they match a certain criteria, while also preventing the mutation of the state as I am using redux.

The code below should work, but I am sure there must be a more succinct way, while also preventing the array being mutated.

state = [
     {
      name: 'larry',
      age 25
    },
    {
      name: 'zach',
      age: 20
    },
    {
      name: 'chuck',
      age: 17 {
        name: 'zach',
        age: 20
      }

]

Redux reducer

case 'REMOVE_LOGIN_ERROR_CONSOLE_MESSAGE':

  for (var i = 0; i < state.length; i++) {
    if (state[i].name = 'zach') {
      delete state[i];
    }
  }

  return [...state];

As I am using redux, I also want to avoid mutating the array.

  • Use `.map()` - create a new array with every object that doesn't have name `zach` and return it - that way the `state` array doesn't change – StudioTime Mar 27 '17 at 09:56
  • 1
    Today I learnt a new word _succinct_. – George Mar 27 '17 at 09:56
  • hahah @George i only learned it last week! :-) cant get enough of it –  Mar 27 '17 at 09:56
  • Can you tried? `function findMatch(arr) { if(arr.name === 'zach') { delete arr.name; } }` `console.log(array.find(findMatch));` – dekts Mar 27 '17 at 09:59
  • I don't think this is a duplicate, any way, this might be the solution you are looking for, return state.filter(item => item.name !== 'zach'); – mfahadi Mar 27 '17 at 10:04
  • @DarrenSweeney cheers for this. strangely map doesnt work. I believe the reason is that `map` returns false. Filter does work however. Does this make sense to you? –  Mar 27 '17 at 10:09
  • 2
    map won't work in this condition, it just transforms the array, can't add or delete items. While filter will return new array except all the items not matching the condition. – mfahadi Mar 27 '17 at 10:12
  • @RaulRodriguez yup, my bad - mfahadi is correct – StudioTime Mar 27 '17 at 10:12
  • @mfahadi feel free to add as an answer. I am sure it will be helpful for somebody going forward –  Mar 27 '17 at 10:13
  • I can't, I guess the question is marked duplicate thats why – mfahadi Mar 27 '17 at 10:15
  • cant create a new question! only allowed once every 90 mins! thanks for your help anyway –  Mar 27 '17 at 10:22

0 Answers0