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


An array in JavaScript is a group of identically typed elements that are stored in adjacent memory locations and may each be separately referred to using an index to a special identifier.

Let’s consider an array consisting of occurrences of repeated names. The array looks like this −

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

Now we are going to count the number of occurrences of repeated names in an array. We use the reduce () concept for this. And the result will be as follows −

John: 1
David: 2

Let’s dive into the article to learn more about how to count number of occurrences of repeated names in an array.

Using reduce()

The reduce() method passes in the return value from the calculation on the previous element and executes a user-supplied "reducer" callback function on each element of the array in turn. Running the reducer across the entire array yields a single value as the end result.

Syntax

Following is the syntax for reduce()

array.reduce(function(total, currentValue, currentIndex, arr), initialValue)

For getting better understanding on counting number of occurrences of repeated names in an array, let’s look into the following examples.

Example

In the following example we are running a script along with a reduce() to print the number of occurrences of repeated names.

<!DOCTYPE html>
<html>
   <body>
      <script>
         var array = [10, 22, 10, 25, 10, 67, 10, 68];
         var search = 10;
         var count = array.reduce(function(n, val) {
            return n + (val === search);
         }, 0);
         document.write(count);
   </script>
   </body>
</html>

When the script gets executed, it will generate an output consisting of the number "4" on the webpage, which is the number of occurrences of the value that was used in the script to count.

Example

Execute the below to look how reduce() was used in getting the count of occurrences of repeated names.

<!DOCTYPE html>
<html>
   <body>
      <script>
         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;
         }, {}));
         document.write(JSON.stringify(output));
      </script>
   </body>
</html>

On running the above script, the output window will pop up, displaying the count of the occurrences of the names caused by the event that gets triggered on running the script.

Let’s consider few more examples.

Example

Consider the following example, here we are declaring a variable that stores the empty object and starting a loop to iterate over the array and print the output.

<!DOCTYPE html>
<html>
   <body>
      <script>
         const array = ['ab', 'bc', 'ab', 'bc', 'cb'];
         const count = {};
         for (const element of array) {
            if (count[element]) {
               count[element] += 1;
            } else {
            count[element] = 1;
            }
         }
         document.write(JSON.stringify(count));
      </script>
   </body>
</html>

When the script gets executed, the event gets triggered and provides the count of the occurrence of repeated elements along with an array on the webpage.

Example

Let’s look at the following example, here we are using foreach to iterate over the array and store the count of occurrences in another variable.

<!DOCTYPE html>
<html>
   <body>
      <script>
         var array = [{
            "car": "rx100",
            "color": "black"
         }, {
            "car": "bmw",
            "color": "grey"
         }, {
            "car": "rx100",
            "color": "black"
         }, ];
         let b = {};
         array.forEach(element => {
            b[element.car] = (b[element.car] || 0) + 1;
         })
         document.write(JSON.stringify(b));
      </script>
   </body>
</html>

On running the above script, the event gets triggered and displays an array along with its count of occurrences on the webpage.

Updated on: 21-Apr-2023

998 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements