Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get rid of duplicates in array of objects

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?

like image 234
BT101 Avatar asked Jan 25 '23 19:01

BT101


2 Answers

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().

like image 59
georg Avatar answered Jan 28 '23 09:01

georg


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"));
like image 44
Nina Scholz Avatar answered Jan 28 '23 11:01

Nina Scholz