To achieve this task, you can utilize the _.countBy()
and _.transform()
functions in order to generate the arrays (check out the example):
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();
Additionally, here is an alternative solution using only JavaScript (view on JSFiddle):
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('output').innerText = JSON.stringify(results);