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 }

Updated on: 20-Nov-2020

487 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements