Calculate mean, median and range in JavaScript
Intermediate · 4 min read
Mean, median and range are the first three numbers people reach for when they want to sum up a list: the average delivery time, the typical house price, how far apart the best and worst test scores are. In this tutorial you will write a small function for each one.
The mean and the range take one line each. The median is where the real lesson is. It needs the numbers in order, and JavaScript's sort has two traps waiting for anyone who sorts numbers. You should know arrays, arrow functions and the spread syntax .... reduce is explained below.
Three ways to describe a list
- The mean is the everyday average: add everything up and divide by how many values there are.
- The median is the middle value once the list is sorted. An even count has two middle values, so you take their average.
- The range is the gap between the biggest and the smallest value.
Here they are, worked out by hand for the readings 4, 1, 9, 1 and 100:
mean: (4 + 1 + 9 + 1 + 100) / 5 = 115 / 5 = 23
median: sorted is 1, 1, 4, 9, 100, so the middle is 4
range: 100 - 1 = 99
Look at how the single 100 drags the mean up to 23, while the median stays at 4. That is why salaries and house prices are usually reported as a median: one mansion doesn't move it.
What about an empty list?
What is the mean of nothing? There is no honest number. 0 looks like a real result, and it would be plotted on a chart as though it were data. NaN ("not a number") is a better answer: any sum you do with NaN is also NaN, so the problem can't quietly hide. All three functions will return NaN for an empty list.
Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.
41 Mean, median and range
fairCompute the mean, the median and the range of a list of numbers. The median is where the work is: it needs the values in order, and an even count has no single middle.
Stuck? Three hints, smallest first
- 1. Sort a copy, with a numeric comparator, or the median of
[10, 9, 1]comes out wrong. - 2. With an even count, average the two middle values.
- 3. Decide what an empty list means.
NaNis more honest than0for a mean.
Step 1: add the numbers up
reduce walks through an array while carrying one value along. Here that value is a running total, t. It starts at 0, the second argument, and each number n is added to it.
const total = (xs) => xs.reduce((t, n) => t + n, 0);
console.log(total([4, 1, 9, 1, 100])); // 115
console.log(total([])); // 0
Starting at 0 also means an empty list gives 0 instead of an error.
Step 2: the mean
const total = (xs) => xs.reduce((t, n) => t + n, 0);
const mean = (xs) => (xs.length === 0 ? NaN : total(xs) / xs.length);
console.log(mean([4, 1, 9, 1, 100])); // 23
console.log(mean([])); // NaN
The ? : is a short if/else. It reads: "if the list is empty, the answer is NaN, otherwise divide the total by the count". Strictly, 0 / 0 is already NaN in JavaScript, but writing the check out makes the choice clear to anyone reading the code.
Step 3: sort a copy, the right way
For the median, the numbers have to be in order. The natural first try is plain sort():
const xs = [10, 9, 1];
console.log([...xs].sort()); // [ 1, 10, 9 ]
console.log([...xs].sort((a, b) => a - b)); // [ 1, 9, 10 ]
The first line is wrong. Without help, sort compares values as text, and as text '10' comes before '9' because '1' comes before '9'. The fix is a compare function. (a, b) => a - b returns a negative number when a is smaller, which tells sort to put a first.
There is a second trap. sort changes the array it is called on. If median sorted xs directly, the caller's list would come back reordered. [...xs] makes a copy first, and only the copy gets sorted.
Step 4: find the middle
With the values in order, the middle position is half the length, rounded down:
const sorted = [1, 1, 4, 9, 100];
const mid = Math.floor(sorted.length / 2);
console.log(mid, sorted[mid]); // 2 4
const even = [1, 2, 3, 4];
const m = Math.floor(even.length / 2);
console.log(even[m - 1], even[m]); // 2 3
console.log((even[m - 1] + even[m]) / 2); // 2.5
Five values give mid = 2, and index 2 is the third value, the true middle. Four values give m = 2 as well, but now there are two middle values, at indexes 1 and 2. Their average, 2.5, is the median.
Step 5: the median function
Put the pieces together. sorted.length % 2 is the remainder after dividing by 2: 1 for an odd count, which counts as true, and 0 for an even count, which counts as false.
function median(xs) {
if (xs.length === 0) return NaN;
const sorted = [...xs].sort((a, b) => a - b);
const mid = Math.floor(sorted.length / 2);
return sorted.length % 2 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2;
}
const readings = [4, 1, 9, 1, 100];
console.log(median(readings)); // 4
console.log(median([1, 2, 3, 4])); // 2.5
console.log(median([10, 9, 1])); // 9
console.log(readings); // [ 4, 1, 9, 1, 100 ]
The last line shows the caller's list is untouched.
Step 6: the range
Math.max and Math.min take separate numbers, not an array, so spread the array into them. The function is called spread here because "range" in code usually means a sequence like 1 to 10.
const spread = (xs) => (xs.length === 0 ? NaN : Math.max(...xs) - Math.min(...xs));
console.log(spread([4, 1, 9, 1, 100])); // 99
console.log(Math.max(...[]) - Math.min(...[])); // -Infinity
The second line shows why the empty check matters. With no values, Math.max returns -Infinity and Math.min returns Infinity, and the difference is -Infinity, which is not a sensible range.
The full solution
The panel has all four functions, runs them on the readings, then shows the median of [10, 9, 1] next to what a default sort would have given. Press Run and read the notes on each line.
const total = (xs) => xs.reduce((t, n) => t + n, 0);
const mean = (xs) => (xs.length === 0 ? NaN : total(xs) / xs.length);
function median(xs) {
if (xs.length === 0) return NaN;
const sorted = [...xs].sort((a, b) => a - b); // a copy, and numeric
const mid = Math.floor(sorted.length / 2);
return sorted.length % 2 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2;
}
const spread = (xs) => (xs.length === 0 ? NaN : Math.max(...xs) - Math.min(...xs));
const readings = [4, 1, 9, 1, 100];
console.log('readings :', readings);
console.log('mean :', mean(readings), '<- dragged upwards by the 100');
console.log('median :', median(readings), '<- unmoved by it');
console.log('range :', spread(readings));
console.log('even count:', median([1, 2, 3, 4]), '<- the average of 2 and 3');
console.log('--- the comparator matters ---');
console.log('median([10, 9, 1]) :', median([10, 9, 1]));
console.log('a default sort gives:', [10, 9, 1].sort(), 'so the middle would be', [10, 9, 1].sort()[1]);
console.log('input afterwards :', readings);
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', mean(readings), 23);
test('the median of an odd count is the middle value', median(readings), 4);
test('the median of an even count averages the two middles', median([1, 2, 3, 4]), 2.5);
test('a numeric comparator gives the right median', median([10, 9, 1]), 9);
test('the default string sort would have said 10', [10, 9, 1].sort()[1], 10);
test('the range', spread(readings), 99);
test('the outlier moves the mean but not the median', mean(readings) > median(readings), true);
test('the median does not disturb its input', readings, [4, 1, 9, 1, 100]);
test('an empty list gives NaN rather than a misleading 0', Number.isNaN(mean([])), true);
median is a two-trap function and both traps are the ones this section keeps returning to. Sorting without copying reorders the caller's data; sorting without a comparator sorts as text, so [10, 9, 1] becomes [1, 10, 9] and the "middle" is 10. The assertions pin down both the right answer and the wrong one.
Returning NaN for an empty list is a deliberate choice. 0 is a plausible-looking mean that hides the fact that there was nothing to average, and it will be plotted on a chart as though it were data. NaN propagates, which is the point.
Common mistakes
- Sorting without a compare function. Numbers get sorted as text, so
[10, 9, 1]becomes[1, 10, 9]and the median comes out as 10. - Sorting the input itself.
xs.sort()reorders the caller's array. Sort a copy made with[...xs]. - Forgetting the even case. Taking
sorted[mid]alone gives 3 for[1, 2, 3, 4]instead of 2.5.
Try it yourself
- Add 1,000 to the readings and compare how far the mean and the median move.
- Write
summary(xs)that returns{ mean, median, range }in one object. - Make
medianignore any value that is not a number, so[3, 'x', 1]gives 2.