How can I subtract one array from another? [duplicate]

风格不统一 提交于 2019-12-13 06:59:27

问题


I have two arrays:

var collectionA = [
    {'name': 'Brandon', 'age': '41'}
];
var collectionB = [
    {'name': 'Brandon', 'age': '41'},
    {'name': 'Tom', 'age': '25'},
    {'name': 'Jimmy', 'age': '36'},
    {'name': 'Brian', 'age': '36'}
];

How can I get create a third array that is basically the result of subtracting collectionA from collectionB? FYI: I'm using Underscore and Backbone in this project and would love to do this with one or the other.

The third array would look like this:

var collectionC = [
    {'name': 'Tom', 'age': '25'},
    {'name': 'Jimmy', 'age': '36'},
    {'name': 'Brian', 'age': '36'}
];

回答1:


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).




回答2:


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);


来源:https://stackoverflow.com/questions/26471049/how-can-i-subtract-one-array-from-another

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!