Given a string or array, return an object (or Map) mapping each item to how many times it appears.
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.
function frequency(items) {
return [...items].reduce((acc, x) => {
acc[x] = (acc[x] || 0) + 1;
return acc;
}, {});
}Frequency maps power 'top N' analytics, detecting the most common error in a log, and the first-non-repeating-character problem.
frequency('constructor') for the char 'c'... but frequency of the word 'constructor' as a key breaks. When does the plain-object version misbehave?