Given a sentence, return a map of each word to its occurrence count, case-insensitively and ignoring punctuation.
Normalize (lowercase), strip punctuation, split on whitespace, then reduce into a counts object. Filter out empty tokens produced by multiple spaces.
function wordCount(sentence) {
return sentence
.toLowerCase()
.replace(/[^a-z0-9\s]/g, '')
.split(/\s+/)
.filter(Boolean)
.reduce((acc, w) => {
acc[w] = (acc[w] || 0) + 1;
return acc;
}, {});
}Word-frequency counting drives log analysis ('most common error message'), simple search relevance, and validating generated test content.
wordCount('Hello, hello world') returns { hello: 1, '': 1, hello: 1, world: 1 } style noise. What two normalizations fix it?