AI Hints
Home›JavaScript Tutorial›Practice: Objects
JavaScript · Lesson 68 of 138

Practice: A Word Counter

Objects as tallies.

⏱ 2 min read▶ Video at 1:22:39🎓 Free
Watch this lesson in the JavaScript courseWatch on YouTube ↗Full JavaScript course

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.

Practice: A Word Counter
From the video: Practice: A Word Counter
  • 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.

app.jsjavascript
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);
Output
{ 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.

keyvalue
TidytoLowerCase + replace
Splitinto words
Tallycounts[w] = (counts[w] ?? 0) + 1
Topsort 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
Next up: Objects Quiz — test yourself