Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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:
-
Split the sentence: Convert the string into an array of words using
split(' ') - Count frequencies: Use an object to store each word and its count
- Create frequency pairs: Transform the object into an array of [word, count] pairs
- Sort by frequency: Sort the array in descending order by count
-
Extract top words: Take the first
numelements 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.
