← Back to libraryQuestion 155 of 468
🧩JavaScript CodingBeginner

Count Character/Element Frequency

📌 Definition:

Given a string or array, return an object (or Map) mapping each item to how many times it appears.

📖 Detailed Explanation:

Iterate once, incrementing a counter per item using reduce or a for-of loop. Use a Map when keys may collide with object prototype names, otherwise a plain object is fine.

💻 Solutions:
function frequency(items) {
  return [...items].reduce((acc, x) => {
    acc[x] = (acc[x] || 0) + 1;
    return acc;
  }, {});
}
🔑 Key Points:
  • (acc[x] || 0) + 1 initializes and increments in one step
  • O(n) single pass
  • Use a Map to avoid prototype-key collisions (e.g. 'constructor')
  • [...items] works for strings and arrays
🌍 Real-World Example:

Frequency maps power 'top N' analytics, detecting the most common error in a log, and the first-non-repeating-character problem.

🎯 Scenario-Based Interview Question:

frequency('constructor') for the char 'c'... but frequency of the word 'constructor' as a key breaks. When does the plain-object version misbehave?