Appraoch 3: Using Array.forEach and Object.keys
Using Array.forEach, count word occurrences in an object. Then, use Object.keys with reduce to iterate over the object’s keys and determine the word with the highest count, resulting in the most frequent word in the string.
Example:
function mostFrequentWord(str) {
const words = str.toLowerCase().match(/\b\w+\b/g);
const wordCount = {};
words.forEach(word => {
wordCount[word] = (wordCount[word] || 0) + 1;
});
return Object.keys(wordCount).reduce((maxWord, word) =>
wordCount[word] > (wordCount[maxWord] || 0) ? word : maxWord, '');
}
console.log(mostFrequentWord("This is a test. This test is only a test."));
Output
test
JavaScript Program to Find the Most Frequent Word in a String
W will 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.
Identifying the most frequent word in a string is a fundamental task in text analysis and processing, important for various applications like natural language processing and data mining. In JavaScript, there are several techniques available to accomplish this task efficiently. In this article, we’ll explore a couple of these approaches, offering clear explanations accompanied by practical examples.
Example:
Input: apple banana apple orange banana apple
Output: apple
Table of Content
- Approach 1: Using an Object to Count Words
- Approach 2: Using Map() to Count Words
- Appraoch 3: Using Array.forEach and Object.keys
- Approach 4: Using Array reduce