Finding n most frequent words from a sentence in JavaScript

JavascriptWeb DevelopmentFront End Technology

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.

For 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 for 3 times while 'a' appears for 2 times in the array and they are the 2 most frequent words in the string.

Example

The code for this will be −

 Live Demo

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 = {};
   strArr.forEach(word => {
      if(map.hasOwnProperty(word)){
         map[word]++;
      }else{
         map[word] = 1;
      }
   });
   const frequencyArr = Object.keys(map).map(key => [key, map[key]]);
   frequencyArr.sort((a, b) => b[1] - a[1]);
   return frequencyArr.slice(0, num).map(el => el[0]);
};
console.log(findMostFrequent(str, num));

Output

And the output in the console will be −

[ 'i', 'a' ]
raja
Published on 27-Feb-2021 06:14:03
Advertisements