Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get duplicates in a JavaScript Array using Underscore

I have an array for which I need to the items that are duplicates and print the items based on a specific property. I know how to get the unique items using underscore.js but I need to find the duplicates instead of the unique values

var somevalue=[{name:"john",country:"spain"},{name:"jane",country:"spain"},{name:"john",country:"italy"},{name:"marry",country:"spain"}]


var uniqueList = _.uniq(somevalue, function (item) {
        return item.name;
    })

This returns:

[{name:"jane",country:"spain"},{name:"marry",country:"spain"}] 

but I actually need the opposite

[{name:"john",country:"spain"},{name:"john",country:"italy"}]
like image 903
Abhishek Dutta Avatar asked Dec 01 '22 18:12

Abhishek Dutta


1 Answers

A purely underscore based approach is:

_.chain(somevalue).groupBy('name').filter(function(v){return v.length > 1}).flatten().value()

This would produce an array of all duplicate, so each duplicate will be in the output array as many times as it is duplicated. If you only want 1 copy of each duplicate, you can simply add a .uniq() to the chain like so:

_.chain(somevalue).groupBy('name').filter(function(v){return v.length > 1}).uniq().value()

No idea how this performs, but I do love my one liners... :-)

like image 132
chmac Avatar answered Dec 04 '22 11:12

chmac