Subscribe

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 precisely what we want, but it can be written way easier and friendlier.

JavaScript array of unique properties

We first need to map input data to an array containing just the categories to get this unique properties array. 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

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

Read next 📖

Removing all vowels with JavaScript

3 Dec, 2022 · 2 min read

Removing all vowels with JavaScript

10 games to learn JavaScript

2 Dec, 2022 · 3 min read

10 games to learn JavaScript

Join 2097 devs and subscribe to my newsletter