Venciity

Most Frequent Word

Jul 20th, 2014
378
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function findMostFreqWord(value) {
  2.     var words = value.match(/\b\w+\b/g);
  3.     var hashTable = [];
  4.     var word;
  5.     var maxTimes = 0;
  6.  
  7.     for (var i in words) {
  8.         word = words[i].toLowerCase();
  9.         if (hashTable[word] === undefined) {
  10.             hashTable[word] = { word: word, times: 1 };
  11.         } else {
  12.             hashTable[word].times++;
  13.         }
  14.  
  15.         if (hashTable[word].times > maxTimes) {
  16.             maxTimes = hashTable[word].times;
  17.         }
  18.     }
  19.  
  20.     var bestWords = [];
  21.    
  22.     // check best words
  23.     for(var j in hashTable) {
  24.         if (hashTable[j].times === maxTimes) {
  25.             bestWords.push(hashTable[j]);
  26.         }
  27.     }
  28.    
  29.     // alphabetical order http://stackoverflow.com/questions/6712034/sort-array-by-firstname-alphabetically-in-javascript
  30.     bestWords.sort(
  31.         function (lhs, rhs) {
  32.         return lhs.word.localeCompare(rhs.word);
  33.         }
  34.     );
  35.    
  36.     // print the result
  37.     for (var k in bestWords) {
  38.         console.log(bestWords[k].word + " -> " + bestWords[k].times + " times");
  39.     }
  40. }
  41.  
  42. findMostFreqWord('in the middle of the night');
  43. findMostFreqWord('Welcome to SoftUni. Welcome to Java. Welcome everyone.');
  44. findMostFreqWord('Hello my friend, hello my darling. Come on, come here. Welcome, welcome darling.');
Advertisement
Add Comment
Please, Sign In to add comment