如何使用Underscore在JavaScript数组中获取重复项

Abh*_*tta 3 javascript underscore.js

我有一个数组,我需要重复项目,并根据特定属性打印项目.我知道如何使用underscore.js获取唯一项目,但我需要找到重复项而不是唯一值

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;
    })
Run Code Online (Sandbox Code Playgroud)

返回:

[{name:"jane",country:"spain"},{name:"marry",country:"spain"}] 
Run Code Online (Sandbox Code Playgroud)

但实际上我需要相反

[{name:"john",country:"spain"},{name:"john",country:"italy"}]
Run Code Online (Sandbox Code Playgroud)

chm*_*mac 12

纯粹基于下划线的方法是:

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

这将产生一个全部重复的数组,因此每个副本将在输出数组中重复多次.如果您只需要每个副本的1个副本,则只需添加一个.uniq()到链中:

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

不知道这是如何表现的,但我确实喜欢我的单排... :-)


Igo*_*min 5

通过uniq数组中的值将.filter()和.where()用于源数组,并获取重复项。

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);
Run Code Online (Sandbox Code Playgroud)

小提琴

如果您有多个重复项,并且代码更干净,则更新第二种方式。

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);
        });
    }
};
Run Code Online (Sandbox Code Playgroud)

看小提琴