Count word frequency in a text in JavaScript
Advanced · 4 min read
Which words does a text use most? Word clouds, search engines, writing tools that warn "you used very twelve times" and spam filters all start by counting words. It is a great beginner project because it joins three skills: pulling words out of text, counting with a Map, and sorting by more than one rule.
In this tutorial you will write wordFrequency, which counts every word in a passage, and ranked, which lists them commonest first with ties in alphabetical order. You should know toLowerCase, for...of loops and how sort takes a compare function. match, Map and ?? are explained below.
Pulling out the words
You could split on spaces, but then mat. would keep its full stop and count as a different word from mat. Instead, match the words directly. text.match(/[a-z']+/g) returns an array of every run of letters and apostrophes, so punctuation and spaces are simply left out.
[a-z'] means "a lowercase letter or an apostrophe", + means "one or more", and g means "find all of them". If nothing matches, match returns null instead of an empty array, so we write || [] to fall back to an empty one.
Counting with a Map
A Map holds key and value pairs. Here the key is a word and the value is how many times we have seen it. counts.get(word) is undefined the first time, so counts.get(word) ?? 0 turns that into 0. The ?? operator means "use the right side if the left side is null or undefined".
Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.
55 Word frequency in a passage
hardCount how often each word appears in a passage and report them commonest first, breaking ties alphabetically.
Stuck? Three hints, smallest first
- 1. Lower-case, then match words rather than splitting, so punctuation is left out.
- 2. Use a
Map: a word could beconstructor. - 3. A two-part comparator sorts by count and then by word.
Step 1: get the words
const passage = 'The cat sat on the mat. The mat was flat.';
console.log(passage.toLowerCase().match(/[a-z']+/g));
// [ 'the', 'cat', 'sat', 'on', 'the', 'mat', 'the', 'mat', 'was', 'flat' ]
Lowercasing first means The and the become the same word. The full stops are gone, because they don't match [a-z'].
Step 2: count them
function wordFrequency(text) {
const counts = new Map();
for (const word of text.toLowerCase().match(/[a-z']+/g) || []) {
counts.set(word, (counts.get(word) ?? 0) + 1);
}
return counts;
}
const freq = wordFrequency('The cat sat on the mat. The mat was flat.');
console.log(freq.get('the')); // 3
console.log(freq.get('mat')); // 2
console.log(freq.size); // 7
console.log(freq.get('lagos')); // undefined
Each word adds one to its count. size is the number of different words. A word that never appeared gives undefined, not 0, so check for that if you look words up.
Step 3: why a Map and not a plain object
It is tempting to count into {}. But every plain object already has some names built in, inherited from Object. One of them is constructor:
console.log(typeof {}.constructor); // 'function'
const counts = {};
counts['constructor'] = (counts['constructor'] ?? 0) + 1;
console.log(typeof counts['constructor']); // 'string'
counts['constructor'] starts as a function, not undefined, so ?? 0 doesn't kick in. Adding 1 to a function turns it into text, and the count becomes a long string with the function's code in it. A Map starts completely empty, so any word is safe as a key.
Step 4: sort, the natural wrong turn
To rank the words, turn the Map into an array of [word, count] pairs and sort by count, largest first:
function wordFrequency(text) {
const counts = new Map();
for (const word of text.toLowerCase().match(/[a-z']+/g) || []) {
counts.set(word, (counts.get(word) ?? 0) + 1);
}
return counts;
}
const byCount = [...wordFrequency('The cat sat on the mat. The mat was flat.').entries()]
.sort((a, b) => b[1] - a[1]);
console.log(byCount.map(([w]) => w)); // [ 'the', 'mat', 'cat', 'sat', 'on', 'was', 'flat' ]
entries() gives the pairs, and [...] turns them into an array. b[1] - a[1] sorts counts from biggest to smallest. The top two are right, but the five words seen once come out in whatever order they first appeared. Reorder the passage and they would come out differently, so a test comparing the full list would break.
Step 5: break ties alphabetically
function wordFrequency(text) {
const counts = new Map();
for (const word of text.toLowerCase().match(/[a-z']+/g) || []) {
counts.set(word, (counts.get(word) ?? 0) + 1);
}
return counts;
}
const ranked = (text) =>
[...wordFrequency(text).entries()].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]));
const top = ranked('The cat sat on the mat. The mat was flat.');
console.log(top[0]); // [ 'the', 3 ]
console.log(top[1]); // [ 'mat', 2 ]
console.log(top.slice(2).map(([w]) => w)); // [ 'cat', 'flat', 'on', 'sat', 'was' ]
When two counts are equal, b[1] - a[1] is 0. Zero counts as false, so || moves on to the right side, a[0].localeCompare(b[0]), which compares the words alphabetically. When counts differ, the subtraction is not 0 and the words are never compared. "First rule, then a tie-breaker" is a pattern you can reuse for any sort.
Step 6: apostrophes stay in
function wordFrequency(text) {
const counts = new Map();
for (const word of text.toLowerCase().match(/[a-z']+/g) || []) {
counts.set(word, (counts.get(word) ?? 0) + 1);
}
return counts;
}
console.log([...wordFrequency("it's it's").keys()]); // [ "it's" ]
console.log(wordFrequency('').size); // 0
Because the pattern includes ', it's is kept as one word. An empty text matches nothing, match returns null, and || [] gives the loop nothing to do. Note what this pattern leaves out: hyphens split well-known into two words, and accented letters are dropped. That is a choice you can change.
The full solution
The panel has wordFrequency and ranked and prints every word of the sample passage with its count, commonest first. Press Run, then read the checks underneath.
function wordFrequency(text) {
const counts = new Map();
for (const word of text.toLowerCase().match(/[a-z']+/g) || []) {
counts.set(word, (counts.get(word) ?? 0) + 1);
}
return counts;
}
// Count descending, then alphabetically, so the order is stable and testable.
const ranked = (text) =>
[...wordFrequency(text).entries()].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]));
const passage = 'The cat sat on the mat. The mat was flat.';
const freq = wordFrequency(passage);
const top = ranked(passage);
for (const [word, n] of top) console.log(word.padEnd(6), n);
Output
11 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 11 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('the commonest word, with its count', top[0], ['the', 3]);
test('and the next', top[1], ['mat', 2]);
test('seven distinct words', freq.size, 7);
test('the full stop is not part of a word', freq.get('mat'), 2);
test('case is folded, so The and the are one word', freq.get('the'), 3);
test('a word that is absent gives undefined, not zero', freq.get('lagos'), undefined);
test('the counts add up to the number of words', [...freq.values()].reduce((a, b) => a + b, 0), 10);
test('an apostrophe is kept inside a word', [...wordFrequency("it's it's").keys()], ["it's"]);
test('a Map is used because a word could be called constructor', wordFrequency('constructor').get('constructor'), 1);
test('where a plain object already has that name on it', typeof {}.constructor, 'function');
test('ties break alphabetically, so the tail is stable', top.slice(2).map(([w]) => w), ['cat', 'flat', 'on', 'sat', 'was']);
Matching words with /[a-z']+/g beats splitting on whitespace, because it drops the punctuation as a side effect instead of needing a second cleaning pass. The cost is that the character class is now a definition of "word" you have to defend — this one keeps apostrophes and loses hyphens and accents.
The tie-break is not cosmetic. Without it the order among equal counts is whatever the Map happened to produce, so the output changes when the input is reordered and the test becomes flaky. b[1] - a[1] || a[0].localeCompare(b[0]) is the general shape: numeric key first, then a deterministic fallback.
The constructor assertion is the reason for the Map. With a plain object, counts['constructor'] starts out as a function, so (counts[w] ?? 0) + 1 produces a string containing a function body.
Common mistakes
- Splitting on spaces. Punctuation sticks to the words, so
matandmat.are counted apart. Match the words instead. - Counting into a plain object. A word like
constructoralready exists on it. Use aMap. - Sorting by count only. Ties come out in a different order when the text changes. Add an alphabetical tie-breaker.
Try it yourself
- Return only the top three words from
ranked. - Ignore common words such as
the,onandwasby skipping a list of "stop words". - Change the pattern so
well-knowncounts as one word andcafékeeps its accent.