Alan Jenshen
Alan Jenshen

Reputation: 3239

opposite of filter es2016

I do below code when I've done removed a user.

users.filter(obj => obj.id === user.id);

It's wrong because now my users object left one user object, instead I should remove the item from the list base on the id. So I wonder is there any opposite of filter function?

Upvotes: 3

Views: 4562

Answers (4)

Zoidbergseasharp
Zoidbergseasharp

Reputation: 4529

If you need to opposite a callback function, you can do this:

myArray.filter((x,y,z) => !callbackFunction(x,y,z));

Upvotes: 1

DannyRosenblatt
DannyRosenblatt

Reputation: 895

JavaScript does not have an opposite function for filter, the way some languages like Ruby do (Array#reject). As mentioned in other answers you should instead negate the condition in the function being passed to filter.

Upvotes: 3

Stanislav Mayorov
Stanislav Mayorov

Reputation: 4452

You should just change condition in callback function.

users.filter(obj => obj.id !== user.id);

Upvotes: 2

slebetman
slebetman

Reputation: 113906

The opposite of filter is filter. You just need to specify what you want to keep.

For example, if you want odd numbers:

[1,2,3,4,5,6].filter(x => x%2 != 0);

if you want the opposite:

[1,2,3,4,5,6].filter(x => x%2 == 0);

Upvotes: 5

Related Questions