JavaScript Count characters case insensitive

JavascriptWeb DevelopmentObject Oriented Programming

We are given a string and are required to write a function that returns the frequency of each character in the array. And we should not take the case of characters into consideration.

To do this the best way would be iterating over the string and preparing an object with key as characters and their frequency as value.

The code for doing this will be −

Example

const string = 'ASASSSASAsaasaBBBASvcdNNSASASxxzccxcv';
const countFrequency = str => {
   const frequency = {};
   for(char of str.toLowerCase()){
      if(!frequency[char]){
         frequency[char] = 1;
      }else{
         frequency[char]++;
      };
   };
   return frequency;
};
console.log(countFrequency(string));

Output

The output of the above code in the console will be −

{ a: 10, s: 11, b: 3, v: 2, c: 4, d: 1, n: 2, x: 3, z: 1 }
raja
Published on 19-Aug-2020 10:54:42
Advertisements