d
Amit DhamuSoftware Engineer
 

Unique values from array of objects

2 minute read 00000 views

Take an array of objects such as:

const cars = [
  {
    make: 'Mercedes',
    model: 'E400',
    colour: 'red',
  },
  {
    make: 'BMW',
    model: '330i',
    colour: 'black',
  },
  {
    make: 'Porsche',
    model: '911',
    colour: 'black',
  },
  {
    make: 'Volkswagen',
    model: 'Gold',
    colour: 'silver',
  },
  {
    make: 'Audi',
    model: 'S3',
    colour: 'silver',
  },
]

We want to grab all of the unique colours and put them into an array (and sort them for good measure).

To do that, we can do:

const colours = cars
  .filter((e, i) => cars.findIndex(o => o.colour == e.colour) === i)
  .map(r => r.colour)
  .sort()

This will give us:

['black', 'red', 'silver']