Sanath
Sanath

Reputation: 4886

using underscore to compare two object lists and obtain the unique objects

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.

Upvotes: 3

Views: 4255

Answers (3)

Joseph
Joseph

Reputation: 938

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

Upvotes: 1

Bergi
Bergi

Reputation: 664405

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

Upvotes: 2

xdazz
xdazz

Reputation: 160833

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

Upvotes: 3

Related Questions