214k views
1 vote
Write the function calcwordfrequencies() in JavaScript that uses the prompt() function to read a list of words (separated by spaces). The function should output those words and their frequencies to the console. For example, if the prompt input is: 'hey hi mark hi mark', the console output should be: 'hey 1 hi 2 mark 2'. Hint: Place unique words in a map, where the key is the word and the associated value is the word's frequency. To test the JavaScript in your web browser, call the calcwordfrequencies() function from the JavaScript console.

1 Answer

0 votes

Final answer:

The calcwordfrequencies() function in JavaScript reads user input with prompt(), uses a map to count word occurrences, and outputs the frequencies to the console.

Step-by-step explanation:

The function calcwordfrequencies() can be written in JavaScript to read a list of words entered by the user and then output the words along with their frequencies to the console. You can use the prompt() function to collect the input and a map to track the frequency of each word. Here's an example implementation:

function calcwordfrequencies() {
var input = prompt('Enter a list of words separated by spaces:');
var words = input.split(' ');
var wordFrequencies = new Map();

for (var word of words)

wordFrequencies.forEach(function(count, word) {
console.log(word + ' ' + count);
});
}

calcwordfrequencies();

This function splits the user input into an array of words, iterates over this array, and then counts the occurrences. The wordFrequencies map holds each unique word and its count. When all words are processed, it logs each word and its count to the console.

User Jasonpgignac
by
7.3k points