- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 };
Example
The code for this will be −
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));
Output
And the output in the console will be −
{ aaa: 2, bbb: 1, ccc: 1 }
Advertisements