How do you count the number of occurrences of repeated names in an array of objects in 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 }
]

Updated on 09-Nov-2020 08:22:52

  • Related Questions & Answers
  • Convert array with duplicate values to object with number of repeated occurrences in JavaScript
  • Unique number of occurrences of elements in an array in JavaScript
  • How to count total number of occurrences of an object in a Python list?
  • Count occurrences of a character in a repeated string in C++
  • How to count the number of occurrences of a character in a string in JavaScript?
  • How to count the number of occurrences of all unique values in an R data frame?
  • Count number of occurrences [or frequency] in a sorted array in C++
  • Count the number of data types in an array - JavaScript
  • Count occurrences of the average of array elements with a given number in C++
  • Count number of occurrences for each char in a string with JavaScript?
  • How to count the number of repeated characters in a Golang String?
  • How to count the number of elements in an array below/above a given number [JavaScript]
  • Return an array with the number of nonoverlapping occurrences of substring in Python
  • How to find the number of occurrences of unique and repeated characters in a string vector in R?
  • Iterating through an array, adding occurrences of a true in JavaScript

Introduction

When working with arrays in JavaScript, we frequently encounter situations that require us to count the number of occurrences of a specific element in that array - this element could be a string, object, number, or even a boolean.

In this article, we will go over several methods for counting the number of occurrences of an element or all elements in a JavaScript array. We'll also take a look at how to count the number of element occurrences in an array of arrays by flattening the array first.

How To Count Element Occurrences Using Loops

The for loop is one of the standard methods to loop through an array. It allows us to loop over each element of an array and compare it to the element we are looking for. That way, we can count the number of occurrences of that element in an array. We can also use it to count the number of occurrences of all elements in the array, but we'll cover that case later in this article. For now, let's assume we want to find the number of occurrences of the specific element.

The Best Solution: for-of Loop

Obviously, JavaScript has a built-in for loop we can use, but, to make things a bit easier, we can use its modification - the for-of loop. That way, instead of accessing each element by its index in the array, we can access the value of the element itself.

Note: JavaScript ES2015 introduced the for-of loop. It is an alternative to array.forEach[] method, previously used to iterate over each element of an array and apply some changes to each of them. The primary difference between for-of and forEach[] is that the first is compatible with async functions. In this article, we've opted to primarily use the for-of loop instead of the forEach[] method just to be safe in an asynchronous scenario, but if you are not bothered with that, feel free to use forEach[] instead!

First of all, let's take a look at how many times a specific element occurs in an array. To accomplish this, we need to set the counter variable to 0, then loop through the array and increase the counter by one each time we find the element we are looking for. When we loop through the entire array, the counter will store the number of occurrences of the element we were searching for:

const allStudentsAge = [19, 22, 18, 19, 16, 18, 19, 21, 24];
let target = 19;

let counter = 0;
for [studentAge of allStudentsAge] {
  if [studentAge == target] {
        counter++;
    }
};

console.log[counter]; // 3

A situation where we have an array of arrays is a bit more complex. In that case, we will first have to flatten the array so all the elements comes into one array using the flat[] method:

const allStudentsAge = [
    [1, 19],
    [3, 4],
    [5, 19],
    [7, 8, 19],
    [10, 11, 12, 13, 14, 15],
    [19, 22, 18, 19, 16, 18, 19, 21, 24]
];

let target = 19;

let counter = 0;
for [studentAge of allStudentsAge.flat[]] {
  if [studentAge == target] {
        counter++;
    }
};

console.log[counter]; // 6

This also works for arrays with elements of different data types. Let's create an example array with various data types and check to see if we can count the number of occurrences of a certain element:

const myArray = [false, 24, "English", false, "english", 22, 19, false, "English", 19];

Now, we can create a reusable function that counts the number of occurrences of the given element in the given array:

const checkOccurrence = [array, element] => {
    let counter = 0;
    for [item of array.flat[]] {
        if [item == element] {
            counter++;
        }
    };
    console.log[counter];
};

Let's check if the function we've created actually works:

checkOccurrence[myArray, false]; // 3
checkOccurrence[myArray, 19]; // 2
checkOccurrence[myArray, "english"]; // 1

We've verified that there are three instances of the element false and two instances of the element 19, which is correct, but why is there only one occurrence of the element "english" instead of three? This is due to case sensitivity of the function we've created - the best way to solve this is to convert all string elements to uppercase [or lowercase] before counting them:

const checkOccurrence = [array, element] => {
    let counter = 0;
    for [item of array.flat[]] {
        if [typeof item === "string"] {
            let newItem = item.toLowerCase[];
            if [newItem == element] {
                counter++;
            }
        } else {
            if [item == element] {
                counter++;
            }
        }
    };
    console.log[counter];
};

When we now count the occurrences of the element "english", the checkOccurrence[] function returns 3 because it is no longer case-sensitive:

checkOccurrence[myArray, "english"]; // 3

Alternative #1: for Loop

If you need to access the index of each element in an array for some reason, you can also use basic for loop instead of for-of :

const checkOccurrence = [array, element] => {
    let counter = 0;
    for [let i = 0; i  {
    let counter = 0;
    array.forEach[]for [let i = 0; i 

Chủ Đề