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;
})
This returns:
[{name:"jane",country:"spain"},{name:"marry",country:"spain"}]
but I actually need the opposite
[{name:"john",country:"spain"},{name:"john",country:"italy"}]
A purely underscore based approach is:
_.chain(somevalue).groupBy('name').filter(function(v){return v.length > 1}).flatten().value()
This would produce an array of all duplicate, so each duplicate will be in the output array as many times as it is duplicated. If you only want 1 copy of each duplicate, you can simply add a .uniq()
to the chain like so:
_.chain(somevalue).groupBy('name').filter(function(v){return v.length > 1}).uniq().value()
No idea how this performs, but I do love my one liners... :-)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With