Medium javascript

Count word frequency

Problem

Count occurrences of each word in "to be or not to be".

Hints
  • Use an object to track counts

Your practice code

Ready — edit the code above and click Run.

Solution

const s = "to be or not to be";
const freq = {};
for (const w of s.split(" ")) freq[w] = (freq[w] || 0) + 1;
console.log(freq);

Try solving on your own first, then reveal the official answer.

Explanation

Object as hash map—same idea as MongoDB $group or SQL GROUP BY.

Toolliyo Assistant
Ask about tutorials, ebooks, training, pricing, mentor services, and support. I use public site content only—not admin or internal tools.

care@toolliyo.com

Need callback? Share your details