Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove an object from an array in Immutable?

Given a state like this:

state = {   things: [     { id: 'a1', name: 'thing 1' },     { id: 'a2', name: 'thing 2' },   ], }; 

How can I create a new state where ID "a1" is removed? It's easy enough to push new items:

return state.set(state.get('things').push(newThing)); 

But I can't figure out how to search for and remove an object by its id property. I tried this:

return state.set('tracks',   state.get('tracks').delete(     state.get('tracks').findIndex(x => x.get('id') === 'a2')   ) ) 

But it seems messy, plus it only works if the item is found, because if findIndex returns -1, that's a valid value for delete.

like image 238
ffxsam Avatar asked Apr 21 '16 06:04

ffxsam


People also ask

How can I remove a specific object from an array?

Pass the value of the element you wish to remove from your array into the indexOf() method to return the index of the element that matches that value in the array. Then make use of the splice() method to remove the element at the returned index.

Can you remove from an array?

To remove an element from an array, we first convert the array to an ArrayList and then use the 'remove' method of ArrayList to remove the element at a particular index. Once removed, we convert the ArrayList back to the array. The following implementation shows removing the element from an array using ArrayList.

Is array slice immutable?

You can create an immutable copy of an array using Array. slice() with no arguments, or with the Array. from() method. It's considered a best practice to do so before manipulating an array.


1 Answers

You can use Array#filter.

return state.set('things', state.get('things').filter(o => o.get('id') !== 'a1')); 
like image 102
Tushar Avatar answered Oct 12 '22 05:10

Tushar