javascript

Calculate the frequency of characters in a string using Javascript

If you want to check how many times a character in a string appeared then you can use below code. It will print the object of string letters with their occuring frequency value.

const str = 'CoNgratulations';

const letters = {};
for (let char of str.toLowerCase()) {
    letters[char] = letters[char] + 1 || 1;
}

console.log(letters);
Output
{"c":1,"o":2,"n":2,"g":1,"r":1,"a":2,"t":2,"u":1,"l":1,"i":1,"s":1}

In the code snippet, there is string str which contains some characters in it. We have converted the string to lowecase so that it does now confuse with capital letters and return the right rest.

We are looping through the string characters and adding 1 in each iteration in the letters object.

Live Demo

Was this helpful?