#3 javascript算法3

1.将2个数组对象中存在相同属性的项出去

# 将 'Num' 值不同的提取出来,想得到结果 [ {"Num": "C " ,"Name": "t3 "} ]
var array1 = [ {"Num": "A "  },{"Num": "B" }];
var array2 = [ {"Num": "A ","Name": "t1 " }, {"Num": "B","Name": "t2"}, {"Num": "C " ,"Name": "t3 "}];
var result = [];
for(var i = 0; i < array2.length; i++){
    var obj = array2[i];
    var num = obj['Num'];
    var isExist = false;
    for(var j = 0; j < array1.length; j++){
        var aj = array1[j];
        var n = aj['Num'];
        if(n == num){
            isExist = true;
            break;
        }
    }
    if(!isExist){
        result.push(obj);
    }
}
console.log(result);
// {"Num": "C " ,"Name": "t3 "}];

使用 lodash 提供的函数 _,remove , _.find

// 将数组arr1和arr2中 ' name="james" '的去除
var arr1 = [
  {name: 'james', age: 12, id: 1},
  {name: 'james', age: 13, id: 2},
  {name: 'tom', age: 14, id: 3},
  {name: 'harry', age: 14, id: 10}
]

var arr2 = [
  {name: 'james', age: 16, id: 4},
  {name: 'louis', age: 13, id: 5},
  {name: 'jimmy', age: 14, id: 3}
]
// _.remove 不是纯函数 会改变数组
_.remove(arr1, function(item1) {
  return _.find(arr2, function(item2) {
    return item1.name === item2.name;
  });
})
console.log(arr1)
[
  { name: 'tom', age: 14, id: 3 },
  { name: 'harry', age: 14, id: 10 }
]

你可能感兴趣的:(#3 javascript算法3)