DNNdrago

15. Most Frequent Word

Jul 24th, 2014
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.14 KB | None | 0 0
  1. function findMostFreqWord(value) {
  2. value = value.toLowerCase();
  3. var allWords = value.match(/\w+/gi);
  4. var words = {};
  5.  
  6. for (var i = 0; i < allWords.length; i += 1) {
  7. if (allWords[i] in words) {
  8. words[allWords[i]] += 1;
  9. }
  10.  
  11. else {
  12. words[allWords[i]] = 1;
  13. }
  14. }
  15.  
  16. var keysSorted = Object.keys(words).
  17. sort(function(a,b){
  18. var compare = words[b]-words[a]
  19. return compare !== 0 ? compare : b < a});
  20.  
  21. var max = words[keysSorted[0]];
  22. var sequence = 1;
  23.  
  24. for(i = 1; i < keysSorted.length; i += 1) {
  25. if(max === words[keysSorted[i]]) {
  26. sequence += 1;
  27. }
  28. else {
  29. break;
  30. }
  31. }
  32.  
  33. for(i = 0; i < sequence; i++) {
  34. console.log(keysSorted[i] + ' -> ' + words[keysSorted[i]] + ' times');
  35. }
  36. }
  37.  
  38.  
  39. findMostFreqWord('in the middle of the night');
  40. findMostFreqWord('Welcome to SoftUni. Welcome to Java. Welcome everyone.');
  41. findMostFreqWord('Hello my friend, hello my darling. Come on, come here. Welcome, welcome darling.');
Advertisement
Add Comment
Please, Sign In to add comment