How to get duplicates in a JavaScript Array using

2019-07-04 15:17发布

问题:

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"}]

回答1:

Use .filter() and .where() for source array by values from uniq array and getting duplicate items.

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

Updated Second way if you have more than one duplicate item, and more clean 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 fiddle



回答2:

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... :-)



回答3:

Here how I have done the same thing:

_.keys(_.pick(_.countBy(somevalue, b=> b.name), (value, key, object) => value > 1))



回答4:

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

//from this you will get the required output