I'm trying to get rid of duplicates in array of objects. I want my code linear so I'm using hashtable:
output = Array.from(new Set(output.map(e => e.company)))
.map(company => { return output.find(e => e.company === company) })
This code works properly for this array of objects:
let output = [
{ company: 'sony'},
{ company: 'sony'},
{ company: 'apple'}
]
but thing is that I want to reuse this code so I would like to move it to function which would take array output
and company
string. I don't know how to do that, I tried like this:
const uniq = (array, key) => {
return Array.from(new Set(array.map( e => e[key] )))
.map(key => { return array.find(e => e[key] === key) })
}
but this return array of two undefined.
Also second thing is that it's pretty complicated code for such trivial task. Isn't there some easier way to do same without losing performance?
This one-liner works with arbitrary objects, not necessarily key:value pairs:
let uniqBy = (a, key) => [...new Map(a.map(x => [x[key], x]).reverse()).values()];
//
let data = [
{company: 'sony', more: 1},
{company: 'apple', more: 1},
{company: 'sony', more: 2},
{company: 'sony', more: 3},
{company: 'apple', more: 3},
]
console.log(uniqBy(data, 'company'))
If you don't care about the order of the result, you can also skip .reverse()
.
You could map the unique values and create a new object.
const
unique = (array, key) => Array.from(new Set(array.map(o => o[key])), value => ({ [key]: value }));
var output = [{ company: 'sony'}, { company: 'sony'}, { company: 'apple'}];
console.log(unique(output, "company"));
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