JavaScript unique object properties from object array

JavaScript unique object properties from object array

Β·

3 min read

The issue at hand, we have an array of objects with specific categories, and I want to have a list of all these categories.

I'll show you how we did this before using a manual loop and how easily this can be done with the Set and Map combination.

Our input array

const data = [
  {id: 1, price: 12, category: 'T-shirt'},
  {id: 2, price: 50, category: 'Jeans'},
  {id: 3, price: 7, category: 'Cap'},
  {id: 4, price: 15, category: 'T-shirt'},
  {id: 5, price: 6.5, category: 'Cap'}
];

As you can see a pretty random array, how do we go about getting the following output?

const output = ['T-shirt', 'Jeans', 'Cap'];

Manually looping (Old-way)

Before Set and Map, we would need to do this. We would choose to have a temporary variable and push values into it based on whether they existed.

let unique = [];
for (let i = 0; i < data.length; i++) {
  if (!unique.includes(data[i].category)) unique.push(data[i].category);
}
// [ 'T-shirt', 'Jeans', 'Cap' ]

The outcome is exactly what we want, but it can be written way easier and nicer.

JavaScript array of unique properties

To get this unique properties array, we first need to map out input data to an array containing just the categories. For this, we will use the Map method.

const mapped = data.map(item => item.category);
// [ 'T-shirt', 'Jeans', 'Cap', 'T-shirt', 'Cap' ]

We map our input data only to return the category, which gives us all the categories.

But, as you can see, we still have duplicates. This is where JavaScript Set comes in handy. It will only keep unique values.

const unique = [...new Set(mapped)];
// [ 'T-shirt', 'Jeans', 'Cap' ]

We can even write this as a one-liner:

const unique = [...new Set(data.map(item => item.category))];

As you can see, this can be super powerful to get unique valued properties quickly.

Thank you for reading, and let's connect!

Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter

Did you find this article valuable?

Support Chris Bongers by becoming a sponsor. Any amount is appreciated!