Advertisement
dimipan80

Most Frequent Word

Nov 12th, 2014
187
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /* Write a JavaScript function findMostFreqWord(str) that finds the most frequent word in a text
  2. and prints it, as well as how many times it appears in format "word -> count".
  3. Consider any non-letter character as a word separator. Ignore the character casing.
  4. If several words have the same maximal frequency, print all of them in alphabetical order.
  5. Write JS program frequentWord.js that invokes your function with the sample input data below
  6. and prints the output at the console. */
  7.  
  8. "use strict";
  9.  
  10. function findMostFreqWord(str) {
  11.     str = str.toLowerCase();
  12.     var wordsArr = str.split(/\W+/).filter(Boolean);
  13.     wordsArr.sort();
  14.     var frequentWords = {};
  15.     for (var i = 0; i < wordsArr.length; i += 1) {
  16.         if (!(frequentWords.hasOwnProperty(wordsArr[i]))) {
  17.             frequentWords[wordsArr[i]] = 0;
  18.             for (var j = 0; j < wordsArr.length; j += 1) {
  19.                 if (wordsArr[j] === wordsArr[i]) {
  20.                     frequentWords[wordsArr[i]]++;
  21.                 }
  22.             }
  23.         }
  24.     }
  25.  
  26.     var maxFrequency = 1;
  27.     for (var prop in frequentWords) {
  28.         if (frequentWords.hasOwnProperty(prop)) {
  29.             if (frequentWords[prop] > maxFrequency) {
  30.                 maxFrequency = frequentWords[prop];
  31.             }
  32.         }
  33.     }
  34.  
  35.     for (prop in frequentWords) {
  36.         if (frequentWords.hasOwnProperty(prop) && frequentWords[prop] == maxFrequency) {
  37.             console.log("%s -> %d times", prop, frequentWords[prop]);
  38.         }
  39.     }
  40. }
  41.  
  42. findMostFreqWord('in the middle of the night');
  43. console.log();
  44. findMostFreqWord('Welcome to SoftUni. Welcome to Java. Welcome everyone.');
  45. console.log();
  46. findMostFreqWord('Hello my friend, hello my darling. Come on, come here. Welcome, welcome darling.');
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement