使用lodash将数组分成非重复数据并仅重复

时间:2015-09-24 14:20:23

标签: javascript arrays lodash

我试图这样做(用lodash):

["place of interest", "sightseeing", "monument", "museum", "sightseeing", "museum", "citylife", "monument", "monument"]

我想要一个没有重复项的数组

["place of interest", "sightseeing", "citylife"]

和一个重复的数组......但没有重复它自己! :)

["museum", "monument"]

1 个答案:

答案 0 :(得分:3)

您可以使用_.countBy()_.transform()创建数组(fiddle):

var arr = ["place of interest", "sightseeing", "monument", "museum", "sightseeing", "museum", "citylife", "monument", "monument"];

_(arr).countBy(function (item) {
    return item;
}).transform(function (result, n, key) {
    result[n === 1 ? 'unique' : 'duplicates'].push(key);
}, { unique : [], duplicates : [] }).value();

这是一个只有JS的解决方案(fiddle):

var arr = ["place of interest", "sightseeing", "monument", "museum", "sightseeing", "museum", "citylife", "monument", "monument"];

var counts = arr.reduce(function (items, item) {
    items[item] = (items[item] || 0) + 1;
    return items;
}, {});

var results = Object.keys(counts).reduce(function (result, key) {
    result[counts[key] === 1 ? 'unique' : 'duplicates'].push(key);
    return result;
}, {
    unique: [],
    duplicates: []
});

console.log(results);

document.getElementById('results').innerText = JSON.stringify(results);