我试图这样做(用lodash):
这
["place of interest", "sightseeing", "monument", "museum", "sightseeing", "museum", "citylife", "monument", "monument"]
我想要一个没有重复项的数组
["place of interest", "sightseeing", "citylife"]
和一个重复的数组......但没有重复它自己! :)
["museum", "monument"]
答案 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);