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
.
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.
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.
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.
You can use Array#filter
.
return state.set('things', state.get('things').filter(o => o.get('id') !== 'a1'));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With