当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - How can I subtract one array from another?

问题描述:

This question already has an answer here:

  • using underscore's “difference” method on objects

    6 answers

网友答案:

You could use _.filter along with _.some on the second collection:

_.filter(collectionB, function(x) { 
    return !_.some(collectionA, function(y) { 
        return y.name == x.name 
    }) 
});

Or equivalently using _.reject:

_.reject(collectionB, function(x) { 
    return _.some(collectionA, function(y) { 
        return y.name == x.name 
    }) 
});

This probably isn't the most efficient though -- if you have large collections you'd probably want something more optimized (ie, make a hash map first to speed up the inner lookup).

网友答案:

SOLUTION

var collectionA = [
    {'name': 'Brandon', 'age': '41'},
    {'name': 'Tom', 'age': '25'},
    {'name': 'Jimmy', 'age': '36'},
    {'name': 'Brian', 'age': '36'}
];
var collectionB = [
    {'name': 'Brandon', 'age': '41'}
];
var subtract = function(a, b){
  var r = {};
  for(var i in a){
    var ai = a[i];
    for(var j in b){
      var bj = b[j];
      if(ai.name != bj.name || ai.age != bj.age){
       r[i] = ai;
      }
    }
  }
  return r;
};

var c = subtract(collectionA,collectionB);
分享给朋友:
您可能感兴趣的文章:
随机阅读: