Function for counting frequency of space separated elements in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

Suppose we have a string that contains some letters separated by whitespaces like this −

const str = 'a b c d a v d e f g q';

We are required to write a JavaScript function that takes in one such string. The function should prepare a frequency array of objects that contains letters and their count.

Example

The code for this will be −

const str = 'a b c d a v d e f g q';
const countFrequency = (str = '') => {
   const result = [];
   const hash = {};
   const words = str.split(" ");
   words.forEach(function (word) {
      word = word.toLowerCase();
      if (word !== "") {
         if (!hash[word]) {
            hash[word] = { name: word, count: 0 };
            result.push(hash[word]);
         };
         hash[word].count++;
      };
   });
   return result.sort((a, b) => b.count − a.count)
}
console.log(countFrequency(str));

Output

And the output in the console will be −

[
   { name: 'a', count: 2 },
   { name: 'd', count: 2 },
   { name: 'b', count: 1 },
   { name: 'c', count: 1 },
   { name: 'v', count: 1 },
   { name: 'e', count: 1 },
   { name: 'f', count: 1 },
   { name: 'g', count: 1 },
   { name: 'q', count: 1 }
]
raja
Published on 25-Nov-2020 11:45:33
Advertisements