Count words frequency using Javascript

Count words frequency using Javascript

In this programming tutorial, you'll see a javascript function to count the frequency of words. Instead of using a third-party npm package, I had to create a custom script to return the number of words as JS Object for a CLI project.


Here is the solution code:

countWords(text) {
    //Edge case: an empty array
    if (text.length === 0) {
      return {};
    //Normalize words
    text = text.toLowerCase();

    /* regular expression to tokenise by word while ignoring punctuation. */
    const pattern = /\w+/g;
    text = text.match(pattern);

    let wordsOccurence = {};

    /* Output an object with results. */
    wordsOccurence = text.reduce((wordsOccurenceMap, word) => {
      if (, word))
        wordsOccurence[word] = 1;
      else wordsOccurence[word] += 1;

      return wordsOccurence;
    }, {});

    return wordsOccurence;

Main Methods

  • Normalizing text to lower case string

You can see that the text we passed to the functions can be normalized by converting to lower case. This is fully customizable that is if you can consider the upper case and lower case separately by updating the code.

  • Tokenising words by Regular Expressions

Another main step is to ignore the punctuations or other symbols from using regular expressions. In our current scenario, we're only taking alphabets for consideration by ignoring all others.

I'll suggest using something like Regex101 for testing out your regular expressions.

  • Reduce words counts into an object

Here, we are using JS reduce function to create JS object of words count.


If you like to know more about JS reduce function, please check out these: JS Array reduce() and How to Use Array Reduce Method in JavaScript.

We created a tool to get the word frequency, please check here.


That's all for now. I hope you got the javascript code solution for creating word frequency. Please like and share this article. Feel free to use the comment option below to give your opinions.

Let's Connect with Makeinfo. Our vision is to create a productive workflow using existing solutions. If you follow us, then you can definitely notice that we are trying our best efforts to make productive solutions with few clicks.

Did you find this article valuable?

Support Dorothi Viki by becoming a sponsor. Any amount is appreciated!