在 Javascript(UnderscoreJS) 中的第二个对象数组的基础上过滤对象数组 1

Filter Object Array 1 on the basis on 2nd Object Array in Javascript(UnderscoreJS)

如果对象数组 1 的对象值不存在于第二个对象数组中,我想过滤它。来自第二个数组的非相交值

> aaa = [{id:1, name:"abc"}, {id:2, name:"xyz"}], 
> bbb = [{group:1}, {group:4}]

> result should be [{id:2, name:"xyz"}]

_.filter(aaa, function(a){
    return _.find(bbb, function(b){
        return b.id !== a.group;
    });
});

但是结果是使用这个代码是错误的。请在这里帮助我

你可以使用 lodash _.reject, which excludes the items who are found. This is opposite of _.filter

_.reject(collection, [predicate=_.identity])

var aaa = [{ id: 1, name: "abc" }, { id: 2, name: "xyz" }],
    bbb = [{ group: 1 }, { group: 4 }],
    result = _.reject(aaa, ({ id }) => _.find(bbb, ({ group }) => group === id));

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>

不是在每次迭代中都使用 find,您可以将不需要的 id 放入 Set 并检查过滤。

var aaa = [{ id: 1, name: "abc" }, { id: 2, name: "xyz" }],
    bbb = [{ group: 1 }, { group: 4 }],
    groups = new Set(bbb.map(({ group }) => group)),
    result = aaa.filter(({ id }) => !groups.has(id));

console.log(result);

这是一个基于下划线的解决方案。

b.id !== a.group -> a.id !== b.group 以匹配对象的结构。

那么, a.id !== b.group -> a.id === b.group 并否定查找结果,以正确过滤您的对象 ;)

const aaa = [{id:1, name:"abc"}, {id:2, name:"xyz"}];
const bbb = [{group:1}, {group:4}];

const result = _.filter(aaa, function(a){
    return !_.find(bbb, function(b){
        return a.id === b.group;
    });
});

console.log(result);
<script src="https://underscorejs.org/underscore-min.js"></script>