Lodash gets elements from an array that do not match an array of values

To get elements from an array corresponding to an array of values, I use this:

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

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

+5
source share
2 answers

This is easy to do with JS Vanilla.

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

The same approach is possible with lodash _.filter() if you should positively use lodash.

ES6 version above:

 var nonMatchingItems = response.filter(item => arrayOfIDs.indexOf(item.id) === -1); // or, shorter var nonMatchingItems = response.filter(item => !arrayOfIDs.includes(item.id)); 
+3
source

You don't need lodash, just use simple javascript; it is also easier to read ...

 function getId (val) { return val.id; } function notMatchId (val) { return arrayOfIDs.indexOf(val) === -1; } var result = response.map(getId).filter(notMatchId); 
+1
source

Source: https://habr.com/ru/post/1247940/


All Articles