Find the number of times a value of an object property occurs in an array with JavaScript?

JavascriptWeb DevelopmentObject Oriented Programming

For this, use the concept of reduce(). Following is the code −

Example

const subjectDetails =
[
   {
      subjectId: '101',
      subjectName: 'JavaScript'
   },
   {
      subjectId: '102',
      subjectName: 'Java'
   },
   {
      subjectId: '103',
      subjectName: 'JavaScript'
   }
];
console.log([...subjectDetails.reduce((obj1, obj2) => {
   if (obj1.has(obj2.subjectName)){
      obj1.get(obj2.subjectName).frequency++;
   } else {
      obj1.set(obj2.subjectName, { subjectName: obj2.subjectName,
      frequency: 1 });
   }
   return obj1;
}, new Map()).values()]);

To run the above program, you need to use the following command −

node fileName.js.

Here, my file name is demo144.js.

Output

This will produce the following output −

PS C:\Users\Amit\JavaScript-code> node demo144.js
[
   { subjectName: 'JavaScript', frequency: 2 },
   { subjectName: 'Java', frequency: 1 }
]
raja
Published on 11-Sep-2020 08:16:22
Advertisements