问题描述:

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.

网友答案:

Unfortunately _.difference does use strict equality, and there is no way to change that by a custom equality callback. You still need to compute 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); })
网友答案:

You could combine 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'));
网友答案:

For those who stumble on this as I did, lodash now has a function called differenceWith which takes a comparator.

_.differenceWith(array, [values], [comparator])

https://lodash.com/docs#differenceWith

相关阅读:
Top