Count occurrences of each value in an array in JavaScript
Intermediate · 3 min read
Counting how often each value appears is called building a frequency count, or a tally. You do it for poll results, for the most common error in a log, for the bestselling product, or for "how many of each" in a shopping basket.
In this tutorial you will count values with a Map and with a plain object, and then find inputs the object gets wrong. By the end you will know which one to reach for. You should know arrays, objects, arrow functions and the basics of reduce.
Map in two minutes
A Map is a built-in collection of key and value pairs. You read with get, write with set, and ask how many keys it has with size. Unlike an object, a Map key can be any value: a number, NaN, or even an object.
const m = new Map();
m.set('bus', 1);
console.log(m.get('bus')); // 1
console.log(m.get('keke')); // undefined
console.log(m.size); // 1
console.log(m.set('keke', 1) === m); // true
The last line matters for this lesson: set returns the map itself. That lets a reduce callback set a value and hand the map on in one expression.
Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.
34 Count how often each value appears
fairCount the occurrences of each value in a list. Do it with a Map and with a plain object, then find two inputs the object gets wrong.
Stuck? Three hints, smallest first
- 1.
map.set(v, (map.get(v) ?? 0) + 1)is the whole loop body, andsetreturns the map. - 2. An object key is a string, so
1and‘1’end up in the same bucket. - 3. A
Mapcan key onNaN, on objects, and on numbers, all kept distinct.
Step 1: count with a Map
For each value, read its count so far (or 0 if this is the first time), add one, and store it.
const countMap = (xs) => xs.reduce((m, v) => m.set(v, (m.get(v) ?? 0) + 1), new Map());
const votes = ['bus', 'keke', 'bus', 'okada', 'bus'];
const counts = countMap(votes);
console.log([...counts]); // [ [ 'bus', 3 ], [ 'keke', 1 ], [ 'okada', 1 ] ]
console.log(counts.get('bus')); // 3
m.get(v) ?? 0 gives the current count, or 0 if get returned undefined. Because set returns the map, the callback returns the map too, with no separate return line. [...counts] turns the map into a list of [key, count] pairs so you can print it.
Step 2: check the total
A quick way to trust a count: the counts should add up to the length of the list.
const countMap = (xs) => xs.reduce((m, v) => m.set(v, (m.get(v) ?? 0) + 1), new Map());
const votes = ['bus', 'keke', 'bus', 'okada', 'bus'];
console.log([...countMap(votes).values()].reduce((t, n) => t + n, 0)); // 5
console.log(countMap([]).size); // 0
Five votes, five counted. An empty list gives an empty map.
Step 3: count with an object
The same idea with a plain object. Here the callback needs a return, because setting a property doesn't give back the object.
const countObject = (xs) => xs.reduce((o, v) => { o[v] = (o[v] ?? 0) + 1; return o; }, {});
console.log(countObject(['bus', 'keke', 'bus', 'okada', 'bus'])); // { bus: 3, keke: 1, okada: 1 }
For a list of words this is perfect, and it prints nicely.
Step 4: where the object goes wrong
Every key of a plain object is a string. Anything you use as a key is turned into text first. Watch what that does to a list with both the number 1 and the string '1':
const countMap = (xs) => xs.reduce((m, v) => m.set(v, (m.get(v) ?? 0) + 1), new Map());
const countObject = (xs) => xs.reduce((o, v) => { o[v] = (o[v] ?? 0) + 1; return o; }, {});
const mixedTypes = [1, '1', 1];
console.log(countObject(mixedTypes)); // { '1': 3 }
console.log([...countMap(mixedTypes)]); // [ [ 1, 2 ], [ '1', 1 ] ]
The object put all three in one bucket, because 1 became '1'. The Map kept them apart: two of the number, one of the string. If your data comes from a form or a CSV file, a mix like this is easy to end up with.
Step 5: NaN, undefined and objects
const countMap = (xs) => xs.reduce((m, v) => m.set(v, (m.get(v) ?? 0) + 1), new Map());
const notNumbers = [NaN, NaN, undefined];
console.log(countMap(notNumbers).get(NaN)); // 2
console.log(countMap(notNumbers).get(undefined)); // 1
const a = {};
const b = {};
console.log(countMap([a, b]).size); // 2
console.log(countMap([a, a]).get(a)); // 2
A Map can count NaN, even though NaN === NaN is false. It uses a rule called SameValueZero, which is like === except that NaN matches itself. An object would turn these keys into the words 'NaN' and 'undefined', and you couldn't tell them apart from real strings that spell those words.
Objects used as keys are counted by identity: a and b look the same but are two different objects, so they get two buckets. The same object twice counts as 2.
The full solution
The panel defines countMap and countObject, counts the votes both ways, and then runs the inputs the object gets wrong. Press Run and compare the two lines for [1, '1', 1].
const countMap = (xs) => xs.reduce((m, v) => m.set(v, (m.get(v) ?? 0) + 1), new Map());
const countObject = (xs) => xs.reduce((o, v) => { o[v] = (o[v] ?? 0) + 1; return o; }, {});
const votes = ['bus', 'keke', 'bus', 'okada', 'bus'];
const mixedTypes = [1, '1', 1];
const notNumbers = [NaN, NaN, undefined];
const a = {};
const b = {};
console.log('votes :', [...countMap(votes)]);
console.log('as an object:', countObject(votes));
console.log('--- what the object cannot do ---');
console.log("[1, '1', 1] object:", countObject(mixedTypes), '<- one bucket');
console.log("[1, '1', 1] Map :", [...countMap(mixedTypes)], '<- two');
console.log('NaN as a Map key :', countMap(notNumbers).get(NaN));
console.log('two empty objects :', countMap([a, b]).size, 'buckets, because keys are identities');
console.log('the same object twice:', countMap([a, a]).get(a));
Output
9 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 9 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('the counts are right', [...countMap(votes)], [['bus', 3], ['keke', 1], ['okada', 1]]);
test('and the total matches the length', [...countMap(votes).values()].reduce((t, n) => t + n, 0), votes.length);
test('an object gives the same answer for string data', countObject(votes), { bus: 3, keke: 1, okada: 1 });
test('but it merges 1 and "1" into one bucket', countObject(mixedTypes), { 1: 3 });
test('while a Map keeps them apart', countMap(mixedTypes).size, 2);
test('a Map can count NaN', countMap(notNumbers).get(NaN), 2);
test('and undefined, without stringifying it', countMap(notNumbers).get(undefined), 1);
test('objects are counted by identity, so two empty ones are two keys', countMap([a, b]).size, 2);
test('an empty list produces an empty map', countMap([]).size, 0);
Also Basic 25, which counts characters in a string. Over an array of arbitrary values the choice of container starts to matter, and the assertions show the two failures a plain object cannot avoid: 1 and '1' collide because every object key is a string, and NaN, undefined and null become the text 'NaN', 'undefined' and 'null' — indistinguishable from strings that happen to spell those words.
A Map keys on the value itself using SameValueZero, so numbers stay numbers, NaN is a usable key, and objects are counted by identity. Use an object for counting words; use a Map for counting anything else.
Common mistakes
- Starting the count at
undefined.undefined + 1isNaN. Use(m.get(v) ?? 0) + 1. - Counting mixed types with an object.
1and'1'land in the same bucket. Use aMap. - Printing a
Mapand expecting an object. Turn it into pairs with[...map], or into an object withObject.fromEntries(map)if all the keys are strings.
Try it yourself
- Count the letters in
'banana'. (Hint:[...'banana']gives you the letters.) - Find the value with the highest count in the votes, using your count and a loop over its entries.
- Count
[true, 'true', 1, '1']with both functions and explain each result.