Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //Course: Software University - Javascript Basics
- //Topic: Loops, Arrays and Strings
- //Homework: Problem 15. Most Frequent Word
- //Write a JavaScript function findMostFreqWord(str) that finds the most frequent word in a text and prints it, as well as how many times it appears in format "word -> count". Consider any non-letter character as a word separator. Ignore the character casing. If several words have the same maximal frequency, print all of them in alphabetical order. Write JS program frequentWord.js that invokes your function with the sample input data below and prints the output at the console.
- function findMostFreqWord(str){
- var strToArr = [];
- var obj = {};
- var word;
- var maxWord = '';
- var maxCount = 1;
- var result = '';
- str = str.replace(/[\.,-\/#!$%\^&\*;:{}=\-_`~()]/g,"").replace(/\s{2,}/g," ");
- strToArr = str.split(" ");
- for (var i=0; i<strToArr.length; i++){
- word = strToArr[i].toLowerCase();
- if (obj[word] == null){
- obj[word] = 1;
- } else {
- obj[word] ++;
- }
- if (obj[word] > maxCount){
- maxWord = word;
- maxCount = obj[word];
- } else if (obj[word] == maxCount){
- maxWord += ", " + word;
- maxCount = obj[word];
- }
- }
- maxWord = maxWord.split(", ").sort(function(a,b){return a>b});
- for (var j=0; j<maxWord.length; j++){
- result += maxWord[j] + " -> " + maxCount + "\n";
- }
- console.log(result);
- }
- findMostFreqWord('in middle the of the The middle middle night');
- findMostFreqWord('Welcome to SoftUni. Welcome to Java. Welcome everyone.');
- findMostFreqWord('Hello my friend, hello my darling. Come on, come here. Welcome, welcome darling.')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement