Word frequency count

Easy TimeO(n log n) SpaceO(n)

Given a block of text, count how often each word appears in it and return the top three words with their counts, most frequent first. Words are compared without regard to case, so "The" and "the" are one word, and punctuation is not part of a word. Each entry comes back as a pair of the word and its count.

Examples

Example 1

Input
text = "the cat and the hat and the bat"
Output
[["the",3],["and",2],["cat",1]]
the appears three times and and twice; cat, hat and bat appear once each, and cat is the one that keeps third place.

Example 2

Input
text = "a b a. B, c"
Output
[["a",2],["b",2],["c",1]]
The full stop, the comma and the capital all fold away, so B is counted as the same word as b.

The Code

function wordFrequency(text) {
  const words = text.toLowerCase().split(/[^a-z]+/);
  const counts = {};
  for (let i = 0; i < words.length; i++) {
    const w = words[i];
    if (w === "") continue;
    counts[w] = (counts[w] || 0) + 1;
  }
  const pairs = Object.keys(counts).map((w) => [w, counts[w]]);
  pairs.sort((x, y) => y[1] - x[1]);
  return pairs.slice(0, 3);
}
wordFrequency("the cat and the hat and the bat");
Done
Step through wordFrequency("the cat and the hat and the bat") call by call