aslv

Most Frequent Word

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