过滤元素的元素,如果包含在其他元素中

时间:2017-12-04 13:00:30

标签: arrays angular typescript

我有两个数组,如下面的格式,

this.originalArray = [{
    id: 10,
    name: 'a',
    roleInfo: [{
        roleID: 5,
        roleName: 'USER'
    }]
},
{
    id: 20,
    name: 'b',
    roleInfo: [{
        roleID: 5,
        roleName: 'Admin',
    }]
 },
 {
     id: 30,
     name: 'c',
     roleInfo: [{
         roleID: 5,
         roleName: 'Support',
     }]
 }]

this.removeElements =      
    roleInfo: [{
        roleID: 5,
        roleName: 'Support',        
}]  

问题:如何过滤removeElements数组中不存在的originalArray

4 个答案:

答案 0 :(得分:0)

你可以做到

var reuslt =  originalArray.filter(item => removeElements.find(test => test.id == item.id));

答案 1 :(得分:-1)

试试这个:

originalArray.filter(item => removeElements.some(f => f.id == item.id));

答案 2 :(得分:-1)

这适用于(几乎)所有浏览器。

var a = [1, 2, 3, 4, 5];
var b = [2, 3];

var result = [], found;
for (var i = 0; i < a.length; i++) {
    found = false;
    // find a[i] in b
    for (var j = 0; j < b.length; j++) {
        if (a[i] == b[j]) {
            found = true;
            break;
        }
    }
    if (!found) {
        result.push(a[i]);
    }
}

或兼容性不是问题

a.filter(i =&gt; b.some(j =&gt; j.id === i.id));

答案 3 :(得分:-1)

this.originalArray =[ { id: 10, name: 'a', roleInfo: [{ roleID: 5, roleName: 'USER' }] },
  { id: 20, name: 'b', roleInfo: [{ roleID: 5, roleName: 'Admin', }] },
   { id: 30, name: 'c', roleInfo: [{ roleID: 5, roleName: 'Support', }] }, ]

   this.removeElements =[
    {
        id: 30,
        name: 'c',
        roleInfo: [{
            roleID: 5,
            roleName: 'Support',
        }]
    }]  

    var finalArr = [];
   this.originalArray.forEach(function(d){
   var filterArr =  this.removeElements.filter(function(d1){
      if(d1.id == d.id && d1.name == d.name){
        return d1;
      }
    });
    if(filterArr.length == 0){
      finalArr.push(d);
    }
   })