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
Check how many objects are in the array with the same key in JavaScript
Suppose, we have an array of objects containing some data about some users like this ?
const arr = [
{
"name":"aaa",
"id":"2100",
"designation":"developer"
},
{
"name":"bbb",
"id":"8888",
"designation":"team lead"
},
{
"name":"ccc",
"id":"6745",
"designation":"manager"
},
{
"name":"aaa",
"id":"9899",
"designation":"sw"
}
];
We are required to write a JavaScript function that takes in one such array. Then our function should return a new object that contains all the name property values mapped to the count of objects that contain that specific name property.
Therefore, for the above array, the output should look like ?
const output = {
"aaa": 2,
"bbb": 1,
"ccc": 1
};
Using for Loop
The traditional approach uses a for loop to iterate through each object and count occurrences:
const arr = [
{
"name":"aaa",
"id":"2100",
"designation":"developer"
},
{
"name":"bbb",
"id":"8888",
"designation":"team lead"
},
{
"name":"ccc",
"id":"6745",
"designation":"manager"
},
{
"name":"aaa",
"id":"9899",
"designation":"sw"
}
];
const countNames = (arr = []) => {
const res = {};
for(let i = 0; i < arr.length; i++){
const { name } = arr[i];
if(res.hasOwnProperty(name)){
res[name]++;
}
else{
res[name] = 1;
};
};
return res;
};
console.log(countNames(arr));
{ aaa: 2, bbb: 1, ccc: 1 }
Using reduce() Method
A more functional approach uses the reduce() method to accumulate counts:
const countNamesReduce = (arr = []) => {
return arr.reduce((acc, obj) => {
acc[obj.name] = (acc[obj.name] || 0) + 1;
return acc;
}, {});
};
console.log(countNamesReduce(arr));
{ aaa: 2, bbb: 1, ccc: 1 }
Using forEach() Method
Another approach uses forEach() for cleaner iteration:
const countNamesForEach = (arr = []) => {
const result = {};
arr.forEach(obj => {
result[obj.name] = (result[obj.name] || 0) + 1;
});
return result;
};
console.log(countNamesForEach(arr));
{ aaa: 2, bbb: 1, ccc: 1 }
Counting Different Keys
The same logic can be applied to count any key, such as designations:
const countDesignations = (arr = []) => {
return arr.reduce((acc, obj) => {
acc[obj.designation] = (acc[obj.designation] || 0) + 1;
return acc;
}, {});
};
console.log(countDesignations(arr));
{ developer: 1, 'team lead': 1, manager: 1, sw: 1 }
Comparison
| Method | Readability | Performance | Use Case |
|---|---|---|---|
| for loop | Good | Fastest | Large datasets |
| reduce() | Excellent | Good | Functional programming |
| forEach() | Good | Good | Simple iteration |
Conclusion
Use reduce() for functional programming style and readability, or for loops for maximum performance. All methods effectively count objects with the same key values in JavaScript arrays.
