Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Count by unique key in JavaScript
When working with arrays of objects, you often need to count occurrences based on unique key values. This is particularly useful for data analysis, grouping records, or creating summary statistics.
The Problem
Given an array of objects with nested properties, we want to count how many times each unique user appears:
const arr = [
{
assigned_user: {
name: 'Paul',
id: 34158
},
doc_status: "processed"
},
{
assigned_user: {
name: 'Simon',
id: 48569
},
doc_status: "processed"
},
{
assigned_user: {
name: 'Simon',
id: 48569
},
doc_status: "processed"
}
];
console.log("Original array length:", arr.length);
Original array length: 3
Using reduce() to Count Unique Keys
The most efficient approach uses reduce() to build a counter object:
const arr = [
{
assigned_user: {
name: 'Paul',
id: 34158
},
doc_status: "processed"
},
{
assigned_user: {
name: 'Simon',
id: 48569
},
doc_status: "processed"
},
{
assigned_user: {
name: 'Simon',
id: 48569
},
doc_status: "processed"
}
];
const countUnique = (arr = []) => {
return arr.reduce((counter, obj) => {
const userName = obj.assigned_user.name;
counter[userName] = (counter[userName] || 0) + 1;
return counter;
}, {});
};
console.log(countUnique(arr));
{ Paul: 1, Simon: 2 }
Converting to Array Format
If you need the result as an array of objects instead of a plain object:
const countUniqueAsArray = (arr = []) => {
const counts = arr.reduce((counter, obj) => {
const userName = obj.assigned_user.name;
counter[userName] = (counter[userName] || 0) + 1;
return counter;
}, {});
return Object.keys(counts).map(userName => ({
user: userName,
count: counts[userName]
}));
};
console.log(countUniqueAsArray(arr));
[ { user: 'Paul', count: 1 }, { user: 'Simon', count: 2 } ]
Counting by Different Keys
You can easily modify this approach to count by any property:
// Count by user ID instead of name
const countByUserId = (arr = []) => {
return arr.reduce((counter, obj) => {
const userId = obj.assigned_user.id;
counter[userId] = (counter[userId] || 0) + 1;
return counter;
}, {});
};
// Count by document status
const countByStatus = (arr = []) => {
return arr.reduce((counter, obj) => {
const status = obj.doc_status;
counter[status] = (counter[status] || 0) + 1;
return counter;
}, {});
};
console.log("By User ID:", countByUserId(arr));
console.log("By Status:", countByStatus(arr));
By User ID: { '34158': 1, '48569': 2 }
By Status: { processed: 3 }
Conclusion
Use reduce() to efficiently count occurrences by unique keys in object arrays. This pattern works for any property and can be easily adapted for different counting scenarios.
Advertisements
