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.
In Lodash, we can deeply compare two objects using the _. isEqual() method. This method will compare both values to determine if they are equivalent.
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])
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.
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 )
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));
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