Check how many objects are in the array with the same key in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

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 }
raja
Published on 21-Nov-2020 15:03:12
Advertisements