最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - lodash get items from array that does not match array of values - Stack Overflow

programmeradmin3浏览0评论

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.

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.

Share Improve this question asked Apr 26, 2016 at 11:59 qr11qr11 4412 gold badges5 silver badges25 bronze badges 0
Add a comment  | 

3 Answers 3

Reset to default 15

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));

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);

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

const result = _.pullAll([...response], arrayOfIDs);
发布评论

评论列表(0)

  1. 暂无评论