Open In App

JavaScript Program to Find the Most Frequent Word in a String

Last Updated : 31 Oct, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we’ll explore a couple of approaches to finding the most frequent word in a string and provide clear explanations along with practical examples. Determining the most frequent word in a string is a common task in text analysis and processing. In JavaScript, we can accomplish this task using various techniques.

Example:

Input: apple banana apple orange banana apple
Output: apple

Approach 1: Using an Object to Count Words

In this approach, we will convert input string into lower case then matching with the regex expression, use an object to keep track of word frequencies, and then find the word with the highest frequency.

Example: Below is the implementation of the above approach

Javascript




function mostFrequentWord(input) {
    const words =
        input.toLowerCase().match(/\b\w+\b/g);
    const frequencyMap = {};
  
    for (const word of words) {
        frequencyMap[word] =
            (frequencyMap[word] || 0) + 1;
    }
  
    let mostFrequent = "";
    let maxFrequency = 0;
  
    for (const word in frequencyMap) 
    {
        if (frequencyMap[word] >
            maxFrequency) 
        {
            maxFrequency = frequencyMap[word];
            mostFrequent = word;
        }
    }
    return mostFrequent;
}
const inputString =
    "apple banana apple orange banana apple";
const frequentWord =
    mostFrequentWord(inputString);
console.log(
    'The most frequent word is: ${frequentWord}');


Output

The most frequent word is: ${frequentWord}

Approach 2: Using Map() to Count Words

This approach utilizes the ES6 Map object to count word frequencies. The Map object provides a convenient way to store key-value pairs.

Example: Below is the implementation of the above approach

Javascript




function mostFrequentWord(input) {
    const words =
        input.toLowerCase().match(/\b\w+\b/g);
    const frequencyMap = new Map();
    for (const word of words) {
        frequencyMap
            .set(word,
                (frequencyMap.get(word) || 0) + 1);
    }
    let mostFrequent = "";
    let maxFrequency = 0;
  
    for (const [word, frequency] of frequencyMap) 
    {
        if (frequency > maxFrequency) 
        {
            maxFrequency = frequency;
            mostFrequent = word;
        }
    }
    return mostFrequent;
}
const inputString =
    "apple banana apple orange banana apple";
const frequentWord =
    mostFrequentWord(inputString);
console.log(
    'The most frequent word is: ${frequentWord}');


Output

The most frequent word is: ${frequentWord}


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads