Computer >> Computer tutorials >  >> Programming >> Javascript

How to count number of occurrences of repeated names in an array - JavaScript?


Let’s say the following is our array −

var details = [
   {
      studentName: "John",
      studentAge: 23
   },
   {
      studentName: "David",
      studentAge: 24
   },
   {
      studentName: "John",
      studentAge: 21
   },
   {
      studentName: "John",
      studentAge: 25
   },
   {
      studentName: "Bob",
      studentAge: 22
   },
   {
      studentName: "David",
      studentAge: 20
   }
]

We need to count of occurrence of repeated names i.e. the output should be

John: 3
David: 2
Bob: 1

For this, you can use the concept of reduce().

Example

Following is the code −

var details = [
   {
      studentName: "John",
      studentAge: 23
   },
   {
      studentName: "David",
      studentAge: 24
   },
   {
      studentName: "John",
      studentAge: 21
   },
   {
      studentName: "John",
      studentAge: 25
   },
   {
      studentName: "Bob",
      studentAge: 22
   },
   {
      studentName: "David",
      studentAge: 20
   }
]
var output = Object.values(details.reduce((obj, { studentName }) => {
   if (obj[studentName] === undefined)
      obj[studentName] = { studentName: studentName, occurrences: 1 };
   else
      obj[studentName].occurrences++;
   return obj;
}, {}));
console.log(output);

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

node fileName.js.

Here, my file name is demo282.js. This will produce the following output on console −

PS C:\Users\Amit\javascript-code> node demo282.js
[
   { studentName: 'John', occurrences: 3 },
   { studentName: 'David', occurrences: 2 },
   { studentName: 'Bob', occurrences: 1 }
]