JavaScript unique object properties from object array


How to create an array of unique properies from an object array

17 Jan, 2021 ยท 2 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 = => 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 = [ Set(mapped)];
// [ 'T-shirt', 'Jeans', 'Cap' ]

We can even write this as a one-liner:

const unique = [ Set( => 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

Spread the knowledge with fellow developers on Twitter
Tweet this tip
Powered by Webmentions - Learn more

Read next ๐Ÿ“–

JavaScript sending data between windows

9 Sep, 2022 ยท 4 min read

JavaScript sending data between windows

Using the native payment request JavaScript API

9 Aug, 2022 ยท 8 min read

Using the native payment request JavaScript API

Join 1829 devs and subscribe to my newsletter