Mean, median and mode in JavaScript
Intermediate · 4 min read
"Average" can mean three different things. The mean adds everything up and divides. The median is the middle value once the list is sorted. The mode is the value that appears most often. Test scores, house prices, survey answers and app ratings all use one or another, and each answers a different question.
In this tutorial you will write all three for the scores [12, 7, 3, 7, 9, 12, 15, 7]. You will handle a list with an even number of items, a list with two modes and an empty list. Along the way you will meet two traps hidden in JavaScript's sort, one of which quietly changes the array you passed in. You need to know reduce, arrow functions and the spread syntax [...xs].
The three averages on a small list
Take [5, 1, 3, 3, 8]:
- Mean: (5 + 1 + 3 + 3 + 8) / 5 = 20 / 5 = 4.
- Median: sorted, it is
[1, 3, 3, 5, 8], and the middle one is 3. - Mode: 3 appears twice, more than anything else, so the mode is 3.
When the list has an even number of items there are two middle values, and the median is halfway between them.
Here is the exercise. Have a go on your own first if you like, then read on and we will build it together.
93 Mean, median and mode
fairCompute all three averages of [12, 7, 3, 7, 9, 12, 15, 7]. Handle an even-length median, more than one mode, and an empty array. Then show why sort() with no comparator is the wrong tool, and what it does to the array you passed in.
Stuck? Three hints, smallest first
- 1. The default
sortcompares strings, so 100 comes before 9. - 2.
sortsorts in place. Copy first with[...xs]. - 3. A dataset can have several modes, or one per value, which means it has none worth reporting.
Step 1: the mean
const add = (a, b) => a + b;
const mean = (xs) => xs.reduce(add, 0) / xs.length;
const scores = [12, 7, 3, 7, 9, 12, 15, 7];
console.log(mean(scores)); // 9
reduce(add, 0) adds everything, starting from 0. The total is 72, and 72 / 8 is exactly 9.
Step 2: the sort trap
To find the median you have to sort. Here is the first trap:
console.log([10, 9, 100, 1].sort()); // [ 1, 10, 100, 9 ]
With no arguments, sort turns every item into text and sorts the text, like words in a dictionary. "100" comes before "9" because "1" comes before "9". To sort numbers, pass a comparator, a function that says which of two items goes first:
console.log([10, 9, 100, 1].sort((a, b) => a - b)); // [ 1, 9, 10, 100 ]
a - b is negative when a is smaller, which tells sort to put a first.
Step 3: the second trap
const inPlace = [10, 9, 100, 1];
inPlace.sort((a, b) => a - b);
console.log(inPlace); // [ 1, 9, 10, 100 ]
const untouched = [10, 9, 100, 1];
const copySorted = [...untouched].sort((a, b) => a - b);
console.log(untouched, copySorted); // [ 10, 9, 100, 1 ] [ 1, 9, 10, 100 ]
sort sorts in place: it changes the array itself. A median function that sorts its input would reorder the caller's data, for example the points on a chart. [...xs] makes a copy first, so the original is left alone.
Step 4: the median
const median = (xs) => {
const sorted = [...xs].sort((a, b) => a - b);
const mid = sorted.length >> 1;
return sorted.length % 2 === 1 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2;
};
console.log(median([5, 1, 3])); // 3
console.log(median(scores)); // 8
console.log(scores.includes(8)); // false
sorted.length >> 1 halves the length and drops any remainder, so it is the middle index. For an odd count, that item is the median. For an even count, take the two items around the middle and average them.
The scores sorted are 3, 7, 7, 7, 9, 12, 12, 15. The middle two are 7 and 9, so the median is 8, a value that is not in the list at all.
Step 5: the mode
const modes = (xs) => {
const counts = new Map();
for (const x of xs) counts.set(x, (counts.get(x) ?? 0) + 1);
const top = Math.max(...counts.values());
return [...counts.keys()].filter((k) => counts.get(k) === top).sort((a, b) => a - b);
};
console.log(modes(scores)); // [ 7 ]
console.log(modes([1, 2, 2, 3, 3, 4]), modes([1, 2, 3])); // [ 2, 3 ] [ 1, 2, 3 ]
A Map keeps a count for each value. counts.get(x) ?? 0 means "the count so far, or 0 if there isn't one yet". Then find the highest count and keep every value that reaches it.
The function returns an array, because a list can have more than one mode. [1, 2, 2, 3, 3, 4] has two. In [1, 2, 3] every value ties, which really means there is no useful mode.
Step 6: an empty list
console.log(mean([]), median([])); // NaN NaN
The mean is 0 / 0, which is NaN. The median adds two undefined values, which also gives NaN. Neither throws, so check for an empty list yourself if it can happen.
Step 7: one outlier
An outlier is a value far away from the rest.
const withOutlier = [12, 7, 3, 7, 9, 12, 1500, 7];
console.log(mean(withOutlier), median(withOutlier)); // 194.625 8
Swap one score for 1500 and the mean jumps from 9 to 194.625. The median doesn't move. That is why incomes and house prices are usually reported as medians.
The full solution
The answer panel has mean, median and modes, and prints the three averages, the odd-length median, the two-mode and all-tie cases, both sort traps, the empty list and the outlier. Press Run to see the output.
const add = (a, b) => a + b;
const mean = (xs) => xs.reduce(add, 0) / xs.length;
const median = (xs) => {
const sorted = [...xs].sort((a, b) => a - b);
const mid = sorted.length >> 1;
return sorted.length % 2 === 1 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2;
};
const modes = (xs) => {
const counts = new Map();
for (const x of xs) counts.set(x, (counts.get(x) ?? 0) + 1);
const top = Math.max(...counts.values());
return [...counts.keys()].filter((k) => counts.get(k) === top).sort((a, b) => a - b);
};
const scores = [12, 7, 3, 7, 9, 12, 15, 7];
const withOutlier = [12, 7, 3, 7, 9, 12, 1500, 7];
// Proof that sort mutates.
const untouched = [10, 9, 100, 1];
const copySorted = [...untouched].sort((a, b) => a - b);
const inPlace = [10, 9, 100, 1];
inPlace.sort((a, b) => a - b);
console.log('mean, median, modes :', mean(scores), median(scores), modes(scores));
console.log('odd length median :', median([5, 1, 3]));
console.log('two modes :', modes([1, 2, 2, 3, 3, 4]), 'all distinct:', modes([1, 2, 3]));
console.log('default sort :', [10, 9, 100, 1].sort());
console.log('after copying :', untouched, copySorted);
console.log('after sorting in place:', inPlace);
console.log('empty :', mean([]), median([]));
console.log('one outlier :', mean(withOutlier), median(withOutlier));
console.log('is the median in the data?', scores.includes(median(scores)));
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 mean is 9, the median 8, and the only mode is 7', [mean(scores), median(scores), modes(scores)], [9, 8, [7]]);
test('an odd-length set has a real middle element', [median([5, 1, 3]), median([5, 1, 3, 9, 2])], [3, 3]);
test('a set can have two modes, or one per value, which means none', [modes([1, 2, 2, 3, 3, 4]), modes([1, 2, 3])], [[2, 3], [1, 2, 3]]);
test('the default sort compares strings, so 100 lands before 9', [[10, 9, 100, 1].sort(), [10, 9, 100, 1].sort((a, b) => a - b)], [[1, 10, 100, 9], [1, 9, 10, 100]]);
test('sort mutates: copying leaves the original alone, sorting in place does not', [untouched, copySorted, inPlace], [[10, 9, 100, 1], [1, 9, 10, 100], [1, 9, 10, 100]]);
test('an empty set gives NaN from both, since 0 / 0 and undefined arithmetic', [Number.isNaN(mean([])), Number.isNaN(median([]))], [true, true]);
test('one outlier moves the mean to 194.625 and leaves the median at 8', [mean(withOutlier), median(withOutlier)], [194.625, 8]);
test('the mean here is exactly 9 because the total 72 divides by 8', [scores.reduce(add, 0), mean(scores) === 9], [72, true]);
test('an even-length median need not be a value that appears in the data', [median(scores), scores.includes(median(scores))], [8, false]);
Two traps, both in sort. Called with no comparator it converts every element to a string and compares those, so [10, 9, 100, 1] becomes [1, 10, 100, 9]. And it sorts in place, so a median function that sorts its argument quietly reorders the caller's array — which is how a "read-only" statistics helper ends up changing the data behind a chart. [...xs].sort((a, b) => a - b) fixes both in one line.
The three averages answer three different questions. The mean uses every value, so a single 1500 in an eight-item set drags it from 9 to 194.625 while the median does not move at all. That robustness is why incomes and house prices are reported as medians. The median of an even-length set is a value that may not appear in the data — 8 is not one of the scores — which matters if you were planning to look it up rather than report it.
Mode is the awkward one, because it is not a function to a single value. [1, 2, 2, 3, 3, 4] has two modes, and [1, 2, 3] has three, which is really a way of saying it has none. Returning an array is the honest signature; returning the first-found maximum hides the ambiguity and makes the answer depend on iteration order.
Common mistakes
- Calling
sort()with no comparator on numbers. It sorts as text, so 100 comes before 9. Use(a, b) => a - b. - Sorting the caller's array.
sortchanges it in place. Copy first with[...xs]. - Returning a single mode. A list can have several. Return them all, or say there is none.
Try it yourself
- Write
range(xs), the largest value minus the smallest. What does it give for the scores with and without the outlier? - Change
modesto return an empty array when every value ties. - Use
toSortedinstead of[...xs].sortinmedian, and check that the original stays unchanged.