Finding n most frequent words from a sentence in JavaScript

For the purpose of this question, we define a sentence as a string that contains English alphabets and punctuations and a word is a substring of that sentence joined together by whitespaces.

We are required to write a JavaScript function that takes in a sentence string, str, as the first argument and a number, num, as the second argument. The function should first count the frequency of each word in the sentence and then return an array of length num containing num most frequent words placed according to decreasing frequencies.

Problem Example

If the input sentence and the number is:

const str = 'i am a good coder and i know that i can solve a problem';
const num = 2;

Then the output should be:

const output = ['i', 'a'];

Because 'i' appears 3 times while 'a' appears 2 times in the sentence, and they are the 2 most frequent words.

Solution

Here's the complete implementation:

const str = 'i am a good coder and i know that i can solve a problem';
const num = 2;

const findMostFrequent = (str = '', num = 1) => {
    const strArr = str.split(' ');
    const map = {};
    
    // Count frequency of each word
    strArr.forEach(word => {
        if(map.hasOwnProperty(word)){
            map[word]++;
        }else{
            map[word] = 1;
        }
    });
    
    // Convert to array of [word, frequency] pairs
    const frequencyArr = Object.keys(map).map(key => [key, map[key]]);
    
    // Sort by frequency in descending order
    frequencyArr.sort((a, b) => b[1] - a[1]);
    
    // Return top num words
    return frequencyArr.slice(0, num).map(el => el[0]);
};

console.log(findMostFrequent(str, num));
[ 'i', 'a' ]

How It Works

The solution follows these steps:

  1. Split the sentence: Convert the string into an array of words using split(' ')
  2. Count frequencies: Use an object to store each word and its count
  3. Create frequency pairs: Transform the object into an array of [word, count] pairs
  4. Sort by frequency: Sort the array in descending order by count
  5. Extract top words: Take the first num elements and extract only the words

Alternative Approach Using Map

const findMostFrequentWithMap = (str = '', num = 1) => {
    const words = str.split(' ');
    const frequencyMap = new Map();
    
    // Count frequencies
    for (const word of words) {
        frequencyMap.set(word, (frequencyMap.get(word) || 0) + 1);
    }
    
    // Sort and return top words
    return Array.from(frequencyMap.entries())
        .sort((a, b) => b[1] - a[1])
        .slice(0, num)
        .map(entry => entry[0]);
};

const testStr = 'hello world hello javascript world hello';
console.log(findMostFrequentWithMap(testStr, 3));
[ 'hello', 'world', 'javascript' ]

Conclusion

Finding the most frequent words involves counting word occurrences and sorting by frequency. The Map approach provides cleaner syntax, while the object approach offers broader compatibility with older JavaScript environments.

Updated on: 2026-03-15T23:19:00+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements