Practice: A Word Counter
Objects as tallies.
How often does each word appear in a piece of text? This is a classic task, used in search engines and text analysis. An object makes a perfect tally, with each word as a key, and its count as the value.

- How often does each word appear?
- Search engines, text analysis
- An object as a tally
Counting words
First, we tidy the text. Lower case, and a regular expression that removes punctuation. Split on spaces gives the words. For each word, we add one to its count, starting from zero if it's new. Then we sort the entries to find the top three. Run it.
const text = "The cat sat. The cat ran! A dog sat, and the dog ran.";
const words = text.toLowerCase().replace(/[^a-z ]/g, "").split(" ");
const counts = {};
for (const w of words) {
counts[w] = (counts[w] ?? 0) + 1;
}
const top = Object.entries(counts).sort((a, b) => b[1] - a[1]).slice(0, 3);
console.log(counts);
console.log("Top 3:", top);{ the: 3, cat: 2, sat: 2, ran: 2, a: 1, dog: 2, and: 1 }
Top 3: [ [ 'the', 3 ], [ 'cat', 2 ], [ 'sat', 2 ] ]The tally pattern
Counts at W equals counts at W, or zero, plus one. You'll write this pattern again and again, to count words, votes, clicks, or errors. JavaScript also has a Map type that's designed for this kind of job. We'll meet it in a later section.
| key | value |
|---|---|
| Tidy | toLowerCase + replace |
| Split | into words |
| Tally | counts[w] = (counts[w] ?? 0) + 1 |
| Top | sort the entries |
Summary
An object works as a tally, with words as keys and counts as values. Next, a quiz on objects.
Key takeaways- Clean, then split
- Tally in an object
- Sort entries for the top