← Back to libraryQuestion 169 of 468
🧩JavaScript CodingIntermediate

Word Frequency in a Sentence

📌 Definition:

Given a sentence, return a map of each word to its occurrence count, case-insensitively and ignoring punctuation.

📖 Detailed Explanation:

Normalize (lowercase), strip punctuation, split on whitespace, then reduce into a counts object. Filter out empty tokens produced by multiple spaces.

💻 Solutions:
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;
    }, {});
}
🔑 Key Points:
  • Normalize case and strip punctuation before splitting
  • split(/\s+/) + filter(Boolean) handles multiple/leading spaces
  • reduce accumulates counts in one pass
  • Consider a Map for very large vocabularies
🌍 Real-World Example:

Word-frequency counting drives log analysis ('most common error message'), simple search relevance, and validating generated test content.

🎯 Scenario-Based Interview Question:

wordCount('Hello, hello world') returns { hello: 1, '': 1, hello: 1, world: 1 } style noise. What two normalizations fix it?