Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* 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. */
- "use strict";
- function findMostFreqWord(str) {
- str = str.toLowerCase();
- var wordsArr = str.split(/\W+/).filter(Boolean);
- wordsArr.sort();
- var frequentWords = {};
- for (var i = 0; i < wordsArr.length; i += 1) {
- if (!(frequentWords.hasOwnProperty(wordsArr[i]))) {
- frequentWords[wordsArr[i]] = 0;
- for (var j = 0; j < wordsArr.length; j += 1) {
- if (wordsArr[j] === wordsArr[i]) {
- frequentWords[wordsArr[i]]++;
- }
- }
- }
- }
- var maxFrequency = 1;
- for (var prop in frequentWords) {
- if (frequentWords.hasOwnProperty(prop)) {
- if (frequentWords[prop] > maxFrequency) {
- maxFrequency = frequentWords[prop];
- }
- }
- }
- for (prop in frequentWords) {
- if (frequentWords.hasOwnProperty(prop) && frequentWords[prop] == maxFrequency) {
- console.log("%s -> %d times", prop, frequentWords[prop]);
- }
- }
- }
- findMostFreqWord('in the middle of the night');
- console.log();
- findMostFreqWord('Welcome to SoftUni. Welcome to Java. Welcome everyone.');
- console.log();
- findMostFreqWord('Hello my friend, hello my darling. Come on, come here. Welcome, welcome darling.');
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement