Unique values from an Array of Objects

How to find unique value from an Array of Objects?

Published 2021-07-16

How to find unique value from an Array of Objects?

Here's a quick and straightforward way to find unique values from a key in an Array of Objects

Let's say we have an Array of Objects and that we want to find all the unique values from a specific key.

Let's take an example with an Array of objects representing our available t-shirts in our store :

const articles = [
  { name: 't-shirt', color: 'yellow' },
  { name: 't-shirt', color: 'yellow' },
  { name: 't-shirt', color: 'green' },
  { name: 't-shirt', color: 'red' },
  { name: 't-shirt', color: 'red' },
];

I want to see all the different colors available :

let colors = []

const uniqueColors = articles.filter(
  (e, i) => articles.findIndex((a) => a.color === e.color) === i
);

uniqueColors.forEach((element) => {
  colors.push(element.color)
});

console.log(`We have ${uniqueColors.length} different colors : ${colors}`)


// 'We have 3 different colors : yellow,green,red'

Related Tutorials :