问题
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