js两个数组比较,找到相同的删除掉

var ary = [1,2,3,4]; 

var  obj=[
   {
     id:1,
     name:'luo1'
   },
   {
     id:2,
     name:'luo2'
   },
   {
     id:5,
     name:'luo5'
   }
]

obj里面的对象id只要在ary里面,就删除掉,

比如最后输出

obj=[{
     id:5,
     name:'luo5'
   }]
阅读 12.1k
4 个回答
unique (obj, ary){
   return obj.filter(function(item){
      return ary.indexOf(item.id) != -1;
   })  
 
}```

const newArr = obj.filter(item => !ary.includes(item.id))

这是一个求集合的补集的问题:
参考文章:
https://stackoverflow.com/que...


// Generic helper function that can be used for the three operations:        
function operation(list1, list2, operationIsUnion) {
    var result = [];
    
    for (var i = 0; i < list1.length; i++) {
        var item1 = list1[i],
            found = false;
        for (var j = 0; j < list2.length; j++) {
            if (item1.userId === list2[j].userId) {
                found = true;
                break;
            }
        }
        if (found === operationIsUnion) {
            result.push(item1);
        }
    }
    return result;
}

// Following functions are to be used:
function inBoth(list1, list2) {
    return operation(list1, list2, true);
}

function inFirstOnly(list1, list2) {
    return operation(list1, list2, false);
}

function inSecondOnly(list1, list2) {
    return inFirstOnly(list2, list1);
}

// Sample data
var list1 = [ {userId:1234,userName:'XYZ'}, 
              {userId:1235,userName:'ABC'}, 
              {userId:1236,userName:'IJKL'},
              {userId:1237,userName:'WXYZ'}, 
              {userId:1238,userName:'LMNO'}
            ];

var list2 = [ {userId:1235,userName:'ABC'},  
              {userId:1236,userName:'IJKL'},
              {userId:1252,userName:'AAAA'}
            ];
  
console.log('inBoth:', inBoth(list1, list2)); 
console.log('inFirstOly:', inFirstOnly(list1, list2)); 
console.log('inSecondOnly:', inSecondOnly(list1, list2)); 

你想得到的解决方案 属于 inSecondOnly

for(var i =0;i<obj.length;i++){

for(var j = 0;j< ary.length;j++){
    if(obj[i].id == ary[j]e){
        obj.splice(i,0);
    }
}

}

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题