Count number of occurrences for each char in a string with JavaScript?


Take an array to store the frequency of each character. If similar character is found, then increment by one otherwise put 1 into that array.

Let’s say the following is our string −

var sentence = "My name is John Smith";

Following is the JavaScript code to count occurrences −

Example

var sentence = "My name is John Smith";
sentence=sentence.toLowerCase();
var noOfCountsOfEachCharacter = {};
var getCharacter, counter, actualLength, noOfCount;
for (counter = 0, actualLength = sentence.length; counter <
actualLength; ++counter) {
   getCharacter = sentence.charAt(counter);
   noOfCount = noOfCountsOfEachCharacter[getCharacter];
   noOfCountsOfEachCharacter[getCharacter] = noOfCount ? noOfCount + 1: 1;
}
for (getCharacter in noOfCountsOfEachCharacter) {
   if(getCharacter!=' ')
   console.log("Character="+getCharacter + " Occurrences=" +
   noOfCountsOfEachCharacter[getCharacter]);
}

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

node fileName.js.

Here, my file name is demo40.js.

Output

This will produce the following output −

PS C:\Users\Amit\JavaScript-code> node demo40.js
Character=m Occurrences=3
Character=y Occurrences=1
Character=n Occurrences=2
Character=a Occurrences=1
Character=e Occurrences=1
Character=i Occurrences=2
Character=s Occurrences=2
Character=j Occurrences=1
Character=o Occurrences=1
Character=h Occurrences=2
Character=t Occurrences=1

Updated on: 01-Sep-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements