Implement the function calcWordFrequencies() that uses a single prompt to read a list of words (separated by spaces). Then, the function outputs those words and their frequencies to the console.

Ex: If the prompt input is:

hey hi Mark hi mark
the console output is:

hey 1
hi 2
Mark 1
hi 2
mark 1

Respuesta :

Answer:

JavaScript code is given below

Explanation:

function calcWordFrequencies() {

   var words = prompt("Enter the sentence below").split(" ");

   var unique_words = [], freqencies = [], count = 0;

   for (var i = 0; i < words.length; i++) {

       var found = false;

       for (var j = 0; j < count; j++) {

           if (words[i] === unique_words[j]) {

               freqencies[j] = freqencies[j] + 1;

               found = true;

           }

       }

       if (!found) {

           unique_words[count] = words[i];

           freqencies[count] = 1;

           count++;

       }

   }

   for (var i = 0; i < words.length; i++) {

       var result = 0;

       for (var j = 0; j < count; j++) {

           if (words[i] === unique_words[j]) {

               result = freqencies[j];

               break;

           }

       }

       console.log(words[i] + " " + result);

   }

}