Count Unique Elements in an Array of Objects by Property in JavaScript



In JavaScript, when dealing with arrays of objects, it's common to need to extract specific values based on object properties and count how many unique occurrences exist for a particular property. Whether you're processing a list of users, products, or any other data structure, counting unique elements by a property is a useful operation.
In this article, we'll discuss how to count the number of unique elements in an array of objects based on a specific property using a few different techniques.

Problem Statement

You have an array of objects representing users, each with properties like name, age, gender, etc. You might want to count how many unique ages, genders, or any other property values are present in this list.

Suppose, we have the following array of objects that contains data about orders placed in a restaurant ?

Input

const users = [
{ name: 'John', age: 25 },
{ name: 'Jane', age: 30 },
{ name: 'Alice', age: 25 },
{ name: 'Bob', age: 30 },
{ name: 'Charlie', age: 35 }
];

You want to count how many unique ages exist in this list.

Output

Number of unique ages: 3

Using Set to Count Unique Values

The Set object in JavaScript is a great choice when you need to ensure uniqueness. A Set automatically removes duplicates, making it a perfect tool for counting unique property values.
Using the map() method to extract the specific property (e.g., age).

users.map(user => user.age)
//creates an array of
ages: [25, 30, 25, 30, 35].
Create a Set to store the unique property values.
new Set() //removes the duplicate values, leaving 

{25, 30, 35}.
Use the .size property to count the number of unique elements.

uniqueAges.size 
// returns the number of unique ages, which is 3.

Example

const users = [
    { name: 'John', age: 25 },
    { name: 'Jane', age: 30 },
    { name: 'Alice', age: 25 },
    { name: 'Bob', age: 30 },
    { name: 'Charlie', age: 35 }
];
// Extract unique ages using Set
const uniqueAges = new Set(users.map(user => user.age));
console.log(`Number of unique ages: ${uniqueAges.size}`);

Output

3

Using reduce() and an Object

Another method is to use the reduce() method along with an object to track unique property values. This approach provides more flexibility, as you can store additional data or perform custom logic during the reduction process.

Example

const users = [
    { name: 'John', age: 25 },
    { name: 'Jane', age: 30 },
    { name: 'Alice', age: 25 },
    { name: 'Bob', age: 30 },
    { name: 'Charlie', age: 35 }
];

// Using reduce to count unique ages
const uniqueAges = users.reduce((acc, user) => {
    acc[user.age] = true;  // Add the age as a key to the accumulator
    return acc;
}, {});

// Output the count of unique ages
console.log(`Number of unique ages: ${Object.keys(uniqueAges).length}`); 

Output

3

Using forEach() with a Set

If you prefer a more manual approach without using map(), you can iterate over the array using forEach() and add the property values to a Set.

Example

const users = [
    { name: 'John', age: 25 },
    { name: 'Jane', age: 30 },
    { name: 'Alice', age: 25 },
    { name: 'Bob', age: 30 },
    { name: 'Charlie', age: 35 }
];
// Initialize a Set to store unique ages
const uniqueAges = new Set();
// Use forEach to add ages to the Set
users.forEach(user => uniqueAges.add(user.age));
// Output the count of unique ages
console.log(`Number of unique ages: ${uniqueAges.size}`);

Output

3

Conclusion

Counting unique elements in an array of objects based on a specific property is a common task in JavaScript. Depending on your preference, you can use different methods such as:
  • Set for simplicity and efficiency.
  • reduce() for more control and flexibility.
  • forEach() for a manual, step-by-step approach.
Each of these methods guarantees a correct count of unique elements in an array based on the chosen property. You can easily adapt them for different types of data, whether you're working with user data, products, or any other array of objects.

Updated on: 2024-12-04T22:05:15+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements