Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove multiple items from Immutable List in one shot

Given this:

state = Immutable.fromJS({
  selectedTrackIds: ['foo', 'bar', 'baz'],
});

Is there a way to get a new state where 'foo' and 'baz' are removed from selectedTrackIds, using a single statement (using only Immutable and plain JS)? Or will I just have to use lodash?

return state.set('selectedTrackIds', Immutable.fromJS(_.difference(
  state.get('selectedTrackIds').toJSON(), ['foo', 'baz']
)));
like image 393
ffxsam Avatar asked Apr 06 '16 07:04

ffxsam


1 Answers

You can use filter to remove the items you don't want:

return state.set('selectedTrackIds',
  state.get('selectedTrackIds').filter(function(x) {
    return ['foo', 'baz'].indexOf(x) < 0; // false return value => remove from list
  })
);

Or combine it with map, and some ES6 syntax:

state.map(x => x.filter(y => ['foo', 'baz'].indexOf(y) < 0))

(filter and map are standard JS, and Immutable provides its own implementations that work directly with Immutable collections)

like image 70
CupawnTae Avatar answered Nov 09 '22 16:11

CupawnTae