Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 635
qr11 Avatar asked Apr 26 '16 11:04

qr11


People also ask

How do I compare two arrays of objects in Lodash?

In Lodash, we can deeply compare two objects using the _. isEqual() method. This method will compare both values to determine if they are equivalent.

What is _ get?

The _. get() function is an inbuilt function in the Underscore. js library of JavaScript which is used to get the value at the path of object. If the resolved value is undefined, the defaultValue is returned in its place. Syntax: _.get(object, path, [defaultValue])

What is Noop Lodash?

The Lodash _. noop() method is used to return “undefined” irrespective of the arguments passed to it. Syntax: _.noop() Parameters: This method can take optional parameters of any type. Returns: This method returns undefined.

What is pickBy Lodash?

Lodash helps in working with arrays, strings, objects, numbers, etc. The _. pickBy() method is used to return a copy of the object that composed of the object properties predicate returns truthy for. Syntax: _.pickBy( object, predicate )


1 Answers

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));
like image 72
Tomalak Avatar answered Sep 22 '22 01:09

Tomalak