How to get duplicates in a JavaScript array using Underscore

I have an array for which I need elements that are duplicated and print the elements based on a specific property. I know how to get unique elements using underscore.js, but I need to find duplicates instead of 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 really need the opposite

[{name:"john",country:"spain"},{name:"john",country:"italy"}]

      

+3


source to share


2 answers


Use .filter () and .where () on the original array by values ​​from the uniq array and getting duplicate elements.

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

var dupArr = [];
somevalue.filter(function(item) {
    var isDupValue = uniqArr.indexOf(item) == -1;

    if (isDupValue)
    {
        dupArr = _.where(somevalue, { name: item.name });
    }
});

console.log(dupArr);

      

Fiddle



Update Second way if you have more than one repeating element and cleaner code.

var dupArr = [];
var groupedByCount = _.countBy(somevalue, function (item) {
    return item.name;
});

for (var name in groupedByCount) {
    if (groupedByCount[name] > 1) {
        _.where(somevalue, {
            name: name
        }).map(function (item) {
            dupArr.push(item);
        });
    }
};

      

Look at the violin

+3


source


An underline-based approach:

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

      

This will create an array of all duplicates, so each duplicate will be in the output array as many times as it is duplicated. If you only want one copy of each duplicate, you can simply add .uniq()

to the chain like this:



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

      

Don't know how it works, but I like my one liners ... :-)

+9


source







All Articles