可以用条件做下划线的“交集”吗?

时间:2015-10-28 07:39:18

标签: javascript angularjs underscore.js

我有两个数组。我需要从第二个数组中通过某些条件从第一个数组中排除元素。我不想做两个循环并检查我的情况。

我无法在下划线中找到它的作用。

angular.forEach(categoryList, function (subcategory) {
  angular.forEach(userPemissions, function (permission) {
    if (permission.AuditCategoryId == subcategory.Id) {
      category.subCategories.push(item);
    }
  });
})

1 个答案:

答案 0 :(得分:1)

尝试

var list1 = [{ id: 1, name: 'foo1' }, { id: 2, name: 'foo2' }, { id: 3, name: 'foo3' }];
var list2 = [{ id: 4, name: 'foo4' }, { id: 2, name: 'foo2' }, { id: 5, name: 'foo5' }];

var result = _.filter(list1, function (item1) {
    return _.some(this, function (item2) {
        return item1.id === item2.id;
    });
}, list2);

console.log(result); //[{ id: 2, name: 'foo2' }]