如何使用Underscore在JavaScript数组中获取重复项 [英] How to get duplicates in a JavaScript Array using Underscore

查看:160
本文介绍了如何使用Underscore在JavaScript数组中获取重复项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

返回:

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

但实际上我需要相反的

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


推荐答案

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

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

小提琴

已更新
如果您有多个重复项目和更干净的代码,则为第二种方式。

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

看小提琴

这篇关于如何使用Underscore在JavaScript数组中获取重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆