

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Count by unique key in JavaScript
Suppose, we have an array of objects like this −
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" } ];
We are required to write a JavaScript function that takes in one such array of objects. The function should then count the number of unique "user" properties that exist in this array of objects.
Then the function should push all such unique objects into a new array and return that array.
Example
The code for this will be −
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 = []) => { let res = []; res = arr.reduce(function (r, o) { let user = o.assigned_user.name; (r[user])? ++r[user] : r[user] = 1; return r; }, {}), result = Object.keys(res).map(function (k) { return {user: k, count: res[k]}; }); return res; } console.log(countUnique(arr));
Output
And the output in the console will be −
{ Paul: 1, Simon: 2 }
- Related Questions & Answers
- Python - Unique values count of each Key
- Primary key Vs Unique key
- Unique Key in RDBMS
- Difference between Primary Key and Unique key
- Count unique elements in array without sorting JavaScript
- JavaScript - Set object key by variable
- Join two objects by key in JavaScript
- JavaScript Count the number of unique elements in an array of objects by an object property?
- Remove unique key from MySQL table?
- Read by key and parse as JSON in JavaScript
- How add unique key to existing table (with non-unique rows)?
- JavaScript function that should count all unique items in an array
- Creating Unique Key in MySQL table referring to date?
- Count Numbers with Unique Digits in C++
- Count unique sublists within list in Python
Advertisements