Find the mode with ties in JavaScript
Intermediate · 4 min read
The mode is the value that appears most often in a list. In 4, 7, 4, 9, 4, 7, the number 4 appears three times, more than anything else, so the mode is 4. Shops use it to find the best-selling shoe size; a survey uses it to find the most common answer.
Unlike the mean and the median, the mode doesn't always give one answer. In 1, 2, 2, 3, 3, 4, both 2 and 3 appear twice. In 5, 6, 7, nothing repeats at all. In this tutorial you will write modes(xs), which returns every value tied for the top count, and an empty list when nothing repeats. You will also see why the counting belongs in a Map rather than a plain object. You need to know arrays, loops and arrow functions.
Counting with a Map
A Map stores pairs of a key and a value. Here the key is an item from the list and the value is how many times you have seen it. get(key) reads a count and set(key, value) writes one.
const counts = new Map();
counts.set(4, 1);
counts.set(4, counts.get(4) + 1);
console.log(counts.get(4)); // 2
console.log(counts.get(9)); // undefined
A key you haven't set gives undefined. That is where ?? helps.
The ?? operator
a ?? b means "use a, unless it is null or undefined, in which case use b". So counts.get(x) ?? 0 gives the count, or 0 the first time you see x.
Here is the exercise. Try it yourself first if you like, then read on and we will build it together.
58 The mode, and what a tie means
fairFind the most frequent value in a list. Return every value that ties for the top count, and nothing at all when no value repeats. Then show why the tally belongs in a Map.
Stuck? Three hints, smallest first
- 1. Tally into a
Map:counts.set(x, (counts.get(x) ?? 0) + 1). - 2. A plain object turns every key into a string, so the number 4 comes back as
"4". - 3. If the highest count is 1, nothing repeated, so there is no mode.
Step 1: tally the list
function tally(xs) {
const counts = new Map();
for (const x of xs) counts.set(x, (counts.get(x) ?? 0) + 1);
return counts;
}
const sizes = [4, 7, 4, 9, 4, 7];
console.log([...tally(sizes)]); // [ [ 4, 3 ], [ 7, 2 ], [ 9, 1 ] ]
For each item, read its count (or 0), add 1 and store it back. Spreading a Map into an array with [...] lists its pairs, in the order the keys first appeared.
Step 2: the highest count
const counts = tally(sizes);
const top = Math.max(...counts.values());
console.log(top); // 3
counts.values() gives the counts 3, 2 and 1. Math.max needs them as separate arguments, so we spread them with ....
Step 3: return every value with that count
The tempting shortcut is to return the first key that has the top count. That works for sizes, but for a tie it quietly picks one winner, usually whichever came first. Returning all of them is honest:
function modes(xs) {
const counts = tally(xs);
const top = Math.max(...counts.values());
return [...counts.keys()].filter((k) => counts.get(k) === top).sort((a, b) => a - b);
}
console.log(modes(sizes)); // [ 4 ]
console.log(modes([1, 2, 2, 3, 3, 4])); // [ 2, 3 ]
filter keeps each key whose count equals the top count. The sort puts the answer in a predictable order. Now try a list with no repeats:
console.log(modes([5, 6, 7])); // [ 5, 6, 7 ]
Every value appears once, so every value "ties". Calling all of them the mode isn't useful.
Step 4: no repeats means no mode
function modes(xs) {
const counts = tally(xs);
const top = Math.max(...counts.values());
if (top === 1) return [];
return [...counts.keys()].filter((k) => counts.get(k) === top).sort((a, b) => a - b);
}
console.log(modes([5, 6, 7])); // []
console.log(modes([])); // []
If the top count is 1, nothing repeated, so we return an empty list. This is a choice, and it is worth writing down so the caller knows.
The empty list works too. Math.max() with nothing to compare is -Infinity, which isn't 1, but there are no keys to filter, so the result is still [].
Step 5: why not a plain object?
Many tutorials count with an object instead, counts[x] = (counts[x] ?? 0) + 1. Look at what happens to the keys:
const asObject = {};
for (const x of [10, 2, 33, 2]) asObject[x] = (asObject[x] ?? 0) + 1;
console.log(Object.keys(asObject)); // [ '2', '10', '33' ]
console.log(typeof Object.keys(asObject)[0]); // string
console.log(typeof [...tally(sizes).keys()][0]); // number
Two problems. Object keys are always strings, so the number 2 comes back as '2', and '2' === 2 is false. And objects list number-like keys in ascending order, not the order they arrived: 10 came first, but '2' is listed first. A Map keeps both the type and the order.
Step 6: it works for any values
console.log([...tally(['yam', 'rice', 'yam'])]); // [ [ 'yam', 2 ], [ 'rice', 1 ] ]
The tally doesn't care what the items are. (The modes sort uses a - b, which is for numbers, so for strings you would sort differently or not at all.)
The full solution
The answer panel has tally and modes, then prints the tally of sizes, the single mode, a tie, the no-repeat case, the same tally in a plain object and a tally of strings. Press Run to see the output.
function tally(xs) {
const counts = new Map();
for (const x of xs) counts.set(x, (counts.get(x) ?? 0) + 1);
return counts;
}
function modes(xs) {
const counts = tally(xs);
const top = Math.max(...counts.values());
if (top === 1) return []; // nothing repeated
return [...counts.keys()].filter((k) => counts.get(k) === top).sort((a, b) => a - b);
}
const sizes = [4, 7, 4, 9, 4, 7];
const tied = [1, 2, 2, 3, 3, 4];
// The same tally in a plain object, for comparison.
const asObject = {};
for (const x of [10, 2, 33, 2]) asObject[x] = (asObject[x] ?? 0) + 1;
const orders = ['yam', 'rice', 'yam'];
console.log('tally :', [...tally(sizes)]);
console.log('mode :', modes(sizes));
console.log('a tie :', modes(tied));
console.log('no repeats:', modes([5, 6, 7]));
console.log('as object :', asObject, 'keys', Object.keys(asObject));
console.log('strings :', [...tally(orders)]);
Output
8 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 8 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('4 appears three times, so it is the only mode', modes(sizes), [4]);
test('2 and 3 both appear twice, and both are modes', modes(tied), [2, 3]);
test('a list with no repeats has no mode at all', modes([5, 6, 7]), []);
test('and neither has an empty list', modes([]), []);
test('a Map keeps the keys as numbers', [typeof [...tally(sizes).keys()][0], [...tally(sizes).keys()]], ['number', [4, 7, 9]]);
test('a plain object turns them into strings', [typeof Object.keys(asObject)[0], Object.keys(asObject)], ['string', ['2', '10', '33']]);
test('and reorders integer-like keys, losing the order they arrived in', Object.keys(asObject).join() === '10,2,33', false);
test('the tally works on anything comparable, not just numbers', [...tally(orders)], [['yam', 2], ['rice', 1]]);
The mode is the only average of the three that need not be a single number, and pretending otherwise is the trap. [1, 2, 2, 3, 3, 4] has two modes; a function returning one of them is picking arbitrarily, usually whichever the tally happened to see first. Return an array and let the caller decide. Deciding that "nothing repeated" means there is no mode is a choice too, and one worth stating.
Use a Map, not an object. Object keys are strings, so counts[4] and counts['4'] are the same slot and the mode comes back as '4' — which then fails === 4. Worse, integer-like keys are enumerated in ascending numeric order rather than insertion order, so the tally silently reorders your data. A Map keeps the key's type and its insertion order.
Common mistakes
- Returning one value for a tie. 1, 2, 2, 3, 3, 4 has two modes. Return an array.
- Counting in a plain object. Keys become strings and get reordered. Use a
Map. - Calling every value a mode. If nothing repeats, every count is 1. Decide what that means; here it returns
[].
Try it yourself
- Find the modes of
[3, 3, 1, 1, 2, 2]. What does your function return, and is that what you want? - Write
modeCount(xs)that returns the highest count itself, for example 3 forsizes. - Change
modesso it works for strings, sorting withlocaleCompare.