LearnFrenzy
Sign in Take a free test

ES6 Features · ES6 Features Coding Problems · Question 8

Word frequency with a Map in JavaScript Solution, output & explanation

  • Program
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 8 Back to Exercise

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.

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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links