How To Count Occurrences of each Element in Array in JavaScript

Count Occurrences of each Element in Array in JavaScript

To count occurrences of each element in array in JavaScript, we used effectively with method using for loop. Check out the details below to get more information.

Count Occurrences of each Element in Array in JavaScript

Let’s follow these steps to count occurrences of each element in array in JavaScript.

Step 1: Declaring a variable and set it to an empty object.

Example 1:

const array = ['L', 'e', 'a', 'n','S','h','a','r','e', 'I', 'T'];
const count = {};

console.log(count);

Output

{}

Step 2: Using the for loop to iterate over the array.

Example 2:

const array = ['L', 'e', 'a', 'n', 'S', 'h', 'a', 'r', 'e', 'I', 'T'];
const count = {};

// The code will count the number of occurrences of a character in array
for (let i = 0; i < array.length; i++) {
  const element = array[i];

  if (count[element]) {
    count[element] += 1;
  } else {
    count[element] = 1;
  }
}

console.log(count); //  {L: 1, e: 2, a: 2, n: 1, S: 1, h: 1, r: 1, I: 1, T: 1}

Output

L: 1
e: 2
a: 2
r: 2
n: 1
S: 1
h: 1
I: 1
T: 1

On each iteration, increment the count by one each time that character appears. This will help you to calculate the number of times the element appears in that array.

Example 3: 

const array = ['L', 'e', 'a', 'r', 'n','S','h','a','r','e', 'I', 'T', '2', '0', '2', '2'];
const count = {};

// The code will count the number of occurrences of a character in array
for (let i = 0; i < array.length; i++) {
  const element = array[i];

  if (count[element]) {
    count[element] += 1;
  } else {
    count[element] = 1;
  }
}

// count character h . output is "1"
console.log("the character h appears", count['h'], "time in the string 'LearnshareIT2022'"); 

// If you try to access the key of the object using a number,
// it will automatically get converted to a string under the hood. output is "3"
console.log("the character h appears", count[2], "time in the string 'LearnshareIT2022'"); 

Output

the character h appears 1 time in the string 'LearnshareIT2022'
the numeric character 2 appears 3 times in the string 'LearnshareIT2022'

Summary

In this tutorial, we have explained how to count occurrences of each element in array in JavaScript by using the declare a variable that stores an empty object and then using for loop to count how many times the character appears in the array. We always hope this tutorial is helpful to you. Leave your comment here if you have any questions or comments to improve the article. Thanks for your read.

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *