Count word frequencies in a sentence with a Map and print the words that appear more than once, most frequent first.
Solution
main.js
const text = "to be or not to be that is the question to ask";
const freq = new Map();
for (const word of text.split(" ")) freq.set(word, (freq.get(word) ?? 0) + 1);
const repeated = [...freq].filter(([, n]) => n > 1).sort((a, b) => b[1] - a[1]);
for (const [word, n] of repeated) console.log(`${word}: ${n}`);
console.log("distinct words:", freq.size);
Output Verified by running it on Node.js
to: 3
be: 2
distinct words: 9
Spreading a Map gives [key, value] pairs, which can be filtered and sorted like any array. size reports the number of distinct words.
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!