qr11
qr11

Reputation: 441

lodash get items from array that does not match array of values

To get items from array that match array of values I use this:

var result =_(response).keyBy('id').at(arrayOfIDs).value();

How can I do the opposite? Get items that does not match array of values.

Upvotes: 10

Views: 13968

Answers (3)

Etienne Tonnelier
Etienne Tonnelier

Reputation: 2229

I think you're looking for the pullAll (https://lodash.com/docs/4.17.15#pullAll) function :

const result = _.pullAll([...response], arrayOfIDs);

Upvotes: 0

Tomalak
Tomalak

Reputation: 338158

This is easily done with vanilla JS.

var nonMatchingItems = response.filter(function (item) {
    return arrayOfIDs.indexOf(item.id) === -1;
});

The same approach is possible with lodash's _.filter(), if you positively must use lodash.

ES6 version of the above:

var nonMatchingItems = response.filter(item => arrayOfIDs.indexOf(item.id) === -1);

// or, shorter
var nonMatchingItems = response.filter(item => !arrayOfIDs.includes(item.id));

Upvotes: 15

sahbeewah
sahbeewah

Reputation: 2690

You don't need lodash, just use plain javascript; it's easier to read as well...

function getId (val) {
    return val.id;
}

function notMatchId (val) {
    return arrayOfIDs.indexOf(val) === -1;
}

var result = response.map(getId).filter(notMatchId);

Upvotes: 0

Related Questions