We have 2 JavaScript object lists.
var AList = [{id:1,name:"AA"},{id:2,name:"BB"},{id:3,name:"CC"},{id:4,name:"DD"},{id:5,name:"EE"},{id:6,name:"FF"}]
var BList = [{id:1,name:"AA"},{id:2,name:"BB"},{id:3,name:"CC"},{id:4,name:"DD"}]
we need to eliminate the duplicates from both lists and return what is unique for AList. (id 5 and 6)
I've used a generic JavaScript implementation for this, but I like to implement a more sleek solution based on underscore.
for(var i=0;i<AList.length;i++){
for(var j=0;j<fBList.length;j++){
if(AList[i] && fBList[j] && (AList[i].id == BList[j].id)){
delete AList[i];
}
}
}
var uniqueList= _.uniq(AList);
After A list is done with deleting the duplicates, there are null elements in place where the duplicates were, therefore we needed to use _uniq
to get a unique set of values.
_.difference(AList,BList)
Doesn't provide the answer.
We have 2 JavaScript object lists.
var AList = [{id:1,name:"AA"},{id:2,name:"BB"},{id:3,name:"CC"},{id:4,name:"DD"},{id:5,name:"EE"},{id:6,name:"FF"}]
var BList = [{id:1,name:"AA"},{id:2,name:"BB"},{id:3,name:"CC"},{id:4,name:"DD"}]
we need to eliminate the duplicates from both lists and return what is unique for AList. (id 5 and 6)
I've used a generic JavaScript implementation for this, but I like to implement a more sleek solution based on underscore.
for(var i=0;i<AList.length;i++){
for(var j=0;j<fBList.length;j++){
if(AList[i] && fBList[j] && (AList[i].id == BList[j].id)){
delete AList[i];
}
}
}
var uniqueList= _.uniq(AList);
After A list is done with deleting the duplicates, there are null elements in place where the duplicates were, therefore we needed to use _uniq
to get a unique set of values.
_.difference(AList,BList)
Doesn't provide the answer.
Share Improve this question edited Jun 4, 2014 at 6:47 Cerbrus 73k19 gold badges136 silver badges150 bronze badges asked Jun 4, 2014 at 6:38 SanathSanath 4,88411 gold badges57 silver badges87 bronze badges3 Answers
Reset to default 3You could bine the two arrays, then get the unique result.
var uniqueList = _.uniq(AList.concat(BList), function(item) {
return item.id;
});
Or you could use _.property(key)
:
var uniqueList = _.uniq(AList.concat(BList), _.property('id'));
Unfortunately _.difference
does use strict equality, and there is no way to change that by a custom equality callback. You still need to pute it manually:
AList = _.uniq(AList, _.property('id'));
BList = _.uniq(BList, _.property('id'));
var bIds = _.pluck(BList, "id");
_.filter(AList, function(el) { return !_.contains(bIds, el.id); })
For those who stumble on this as I did, lodash now has a function called differenceWith
which takes a parator.
_.differenceWith(array, [values], [parator])
https://lodash./docs#differenceWith