Find the mode of an array in JavaScript
Intermediate · 4 min read
The mode is the value that shows up most often in a list: the most popular way to get to work, the shoe size a shop should stock most of, the answer most people picked in a poll. In this tutorial you will write a function that finds it.
There is a catch that most quick answers skip. A list can have more than one mode. In [1, 1, 2, 2], both 1 and 2 appear twice, and neither is "the" answer. You will write a version that reports ties honestly. You should know arrays, arrow functions and reduce. Map is explained below.
Counting with a Map
To find the most common value, you first count every value. A Map is a good place to keep those counts. It stores pairs of a key and a value:
const counts = new Map();
counts.set('bus', 1);
console.log(counts.get('bus')); // 1
console.log(counts.get('keke')); // undefined
console.log(counts.get('keke') ?? 0); // 0
get returns undefined for a key that isn't there yet. The ?? operator means "use the right side when the left side is undefined or null", so counts.get(v) ?? 0 reads as "the count so far, or 0".
Why not a plain object? An object turns every key into a string, so the number 1 and the text '1' land in the same slot. A Map keeps them apart:
const obj = {};
obj[1] = 'number';
obj['1'] = 'string';
console.log(Object.keys(obj)); // [ '1' ]
const map = new Map([[1, 'number'], ['1', 'string']]);
console.log(map.size); // 2
A Map also remembers the order keys were first added, which will decide the order of tied modes.
What should the answer be?
Three situations need a decision:
- One clear winner. Return it.
- A tie. Return every tied value. Only the caller knows which one they want, so the function shouldn't pick for them.
- An empty list. There is no mode, so return an empty list.
Returning an array every time handles all three. One winner is an array of one.
Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.
42 The mode, including ties
fairFind the most frequent value. Decide what to return when two values tie, and when every value appears once.
Stuck? Three hints, smallest first
- 1. Count first, then find the highest count, then collect every value with that count.
- 2. Returning an array handles ties honestly; returning one value forces you to pick.
- 3. A
Mapkeeps insertion order, so tied modes come out in first-seen order.
Step 1: count every value
reduce carries the Map along. For each value it sets the count to "the old count plus one". set returns the map itself, so the arrow function can return it straight away for the next round.
const trips = ['bus', 'keke', 'bus', 'okada', 'bus'];
const counts = trips.reduce((m, v) => m.set(v, (m.get(v) ?? 0) + 1), new Map());
console.log(counts); // Map(3) { 'bus' => 3, 'keke' => 1, 'okada' => 1 }
Step 2: find the highest count
counts.values() gives you just the counts. Spread them into Math.max:
const counts = new Map([['bus', 3], ['keke', 1], ['okada', 1]]);
console.log([...counts.values()]); // [ 3, 1, 1 ]
const best = Math.max(...counts.values());
console.log(best); // 3
Step 3: collect every value with that count
Spreading the whole map gives [key, count] pairs. Keep the pairs whose count equals best, then keep only the key from each:
const counts = new Map([['bus', 3], ['keke', 1], ['okada', 1]]);
const best = 3;
console.log([...counts]); // [ [ 'bus', 3 ], [ 'keke', 1 ], [ 'okada', 1 ] ]
console.log([...counts].filter(([, n]) => n === best).map(([v]) => v)); // [ 'bus' ]
([, n]) unpacks each pair. The empty spot before the comma skips the key, so n is the count. ([v]) takes just the key.
Why filter and not find? find stops at the first match. On a tie it would quietly return one value and drop the other, which is exactly what we decided not to do.
Step 4: put it together
function modes(xs) {
const counts = xs.reduce((m, v) => m.set(v, (m.get(v) ?? 0) + 1), new Map());
if (counts.size === 0) return [];
const best = Math.max(...counts.values());
return [...counts].filter(([, n]) => n === best).map(([v]) => v);
}
console.log(modes(['bus', 'keke', 'bus', 'okada', 'bus'])); // [ 'bus' ]
console.log(modes([1, 1, 2, 2])); // [ 1, 2 ]
console.log(modes([2, 2, 1, 1])); // [ 2, 1 ]
console.log(modes([1, 2, 3])); // [ 1, 2, 3 ]
console.log(modes([])); // []
console.log(modes([NaN, NaN, 1])); // [ NaN ]
The counts.size === 0 line handles the empty list. Without it, Math.max() with nothing to compare returns -Infinity, and the result would still be empty, but only by luck.
Ties come out in the order the values first appeared: [2, 2, 1, 1] gives [2, 1]. When every value appears once, they all tie at one, so every value is a mode. And NaN can be a mode, because a Map treats two NaN keys as the same key.
Step 5: when you need one answer
Sometimes the code that calls you needs a single value. Then pick one on purpose, and say in the name which one you picked:
function modes(xs) {
const counts = xs.reduce((m, v) => m.set(v, (m.get(v) ?? 0) + 1), new Map());
if (counts.size === 0) return [];
const best = Math.max(...counts.values());
return [...counts].filter(([, n]) => n === best).map(([v]) => v);
}
const firstMode = (xs) => modes(xs)[0];
console.log(firstMode([2, 2, 1, 1])); // 2
Anyone reading firstMode knows a tie was settled by "whichever came first".
The full solution
The panel has modes and firstMode, and runs them on a list of trips, a tie, an all-different list, an empty list and a list with NaN. Press Run and check each result against the steps above.
function modes(xs) {
const counts = xs.reduce((m, v) => m.set(v, (m.get(v) ?? 0) + 1), new Map());
if (counts.size === 0) return [];
const best = Math.max(...counts.values());
return [...counts].filter(([, n]) => n === best).map(([v]) => v);
}
// When one answer is required, say in the name which one you took.
const firstMode = (xs) => modes(xs)[0];
const trips = ['bus', 'keke', 'bus', 'okada', 'bus'];
console.log('modes(trips) :', modes(trips));
console.log('a tie :', modes([1, 1, 2, 2]), '<- both, in first-seen order');
console.log('all distinct :', modes([1, 2, 3]), '<- everything ties at one');
console.log('empty :', modes([]));
console.log('firstMode of a tie:', firstMode([2, 2, 1, 1]));
console.log('NaN can be a mode :', modes([NaN, NaN, 1]).map(String));
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('a single mode', modes([1, 2, 2, 3]), [2]);
test('the mode of a list of words', modes(trips), ['bus']);
test('a tie returns both values', modes([1, 1, 2, 2]), [1, 2]);
test('in first-seen order', modes([2, 2, 1, 1]), [2, 1]);
test('all-distinct means everything is a mode', modes([1, 2, 3]), [1, 2, 3]);
test('an empty list has no mode at all', modes([]), []);
test('NaN can be the mode, because the counter is a Map', modes([NaN, NaN, 1]).length, 1);
test('and it really is NaN, not the string', Number.isNaN(modes([NaN, NaN, 1])[0]), true);
test('picking one answer from a tie is a choice you have to name', firstMode([2, 2, 1, 1]), 2);
The mode is the only one of the three averages that can legitimately have several answers, and most implementations quietly return the first one they happen to find. Returning an array makes the tie visible to the caller, who is the only one who can decide what to do about it.
Two edge cases decide whether an implementation is any good: every value appearing once (every value is a mode, tied at 1) and the empty list (no mode exists, so [] rather than undefined in an array). The Map counter is what allows NaN to be a mode at all — an object accumulator would have turned it into the string 'NaN', as exercise 34 showed.
Common mistakes
- Returning only the first winner. A tie silently loses values. Return an array of every value with the top count.
- Counting in a plain object. Keys become strings, so
1and'1'are counted together andNaNturns into the text'NaN'. - Forgetting the empty list. Decide what it means. An empty array says "no mode" clearly.
Try it yourself
- Find the modes of the letters in
'banana'. (Hint:[...'banana']gives the letters.) - Write
modeCount(xs)that returns how many times the mode appears. - Change
modesso that when every value appears exactly once, it returns[]instead.