/

How to Retrieve Unique Properties from an Array of JavaScript Objects

How to Retrieve Unique Properties from an Array of JavaScript Objects

When working with an array of objects in JavaScript, there may be times when you need to extract the unique values of a specific property from these objects. This can be achieved by utilizing the set of built-in JavaScript functions and operators. Let’s take a look at an example to better understand how this can be done.

Suppose we have an array called bills, which contains several objects representing different bills, each with properties such as date, amount, and category. We want to extract the unique values of the category property from each object in the array.

Here’s the array of bills:

1
2
3
4
5
const bills = [
{ date: '2018-01-20', amount: '220', category: 'Electricity' },
{ date: '2018-01-20', amount: '20', category: 'Gas' },
{ date: '2018-02-20', amount: '120', category: 'Electricity' }
]

To retrieve the unique values of the category property from the array, we can use the following code:

1
const categories = [...new Set(bills.map(bill => bill.category))];

Let’s break down this code and understand how it works.

Explanation:

In this example, we utilize the Set data structure, introduced in ES6, which is a collection of unique values. By using the map() function, we extract the values of the category property from each object in the bills array. The result of the mapping operation is an array:

1
['Electricity', 'Gas', 'Electricity']

By passing this array into the Set constructor, we automatically remove any duplicate values, resulting in a set of unique values. However, to work with these values more easily, we then utilize the spread operator (...) to expand the set values into a new array, categories.

The final result will be an array categories that contains the unique values of the category property extracted from the bills array.

In this way, you can easily retrieve the unique values of a specific property from an array of JavaScript objects.

Tags: JavaScript, array, objects, unique values, properties.