Find the median of an array in JavaScript
Beginner · 4 min read
The median is the middle value of a list once it is sorted. For 3, 1 and 2, sort them to 1, 2, 3 and the median is 2. When the list has an even number of values there is no single middle, so you take the average of the two middle ones: the median of 1, 2, 3, 4 is 2.5.
The median is how house prices and incomes are usually reported, because one huge value barely moves it. In this tutorial you will write median(xs), and on the way you will meet two traps in JavaScript's sort method: it sorts numbers as if they were words, and it changes the array you pass in. You need to know arrays and arrow functions.
How sort compares by default
sort() with nothing inside the brackets turns every item into a string and compares the strings letter by letter, like a dictionary. For words that is what you want. For numbers it isn't:
console.log([5, 40, 300, 1000].sort()); // [ 1000, 300, 40, 5 ]
As strings, '1000' starts with '1', which comes before '3', '4' and '5'. So 1000 sorts first.
The compare function
To sort numbers, you give sort a compare function. It receives two items, a and b, and returns a negative number if a should come first, a positive number if b should, and 0 if it doesn't matter. (a, b) => a - b does exactly that for numbers, smallest first.
Here is the exercise. Try it yourself first if you like, then read on and we will build it together.
57 The median, and the sort that ruins it
easyFind the middle value of a list, averaging the two middle values when the count is even. Then show what [5, 40, 300, 1000].sort() does, and prove your function leaves the caller's array alone.
Stuck? Three hints, smallest first
- 1.
sortwith no comparator compares strings, so 1000 sorts before 5. - 2.
sortalso mutates in place, so sort a copy. - 3. For an even count there is no single middle: take the mean of the two.
Step 1: sort numbers properly
const wide = [5, 40, 300, 1000];
console.log(wide.slice().sort((a, b) => a - b)); // [ 5, 40, 300, 1000 ]
With the compare function, the order is numeric. The .slice() is there for the next trap.
Step 2: sort changes the original array
sort doesn't make a new array. It rearranges the one you call it on, and returns that same array:
const caller = [3, 1, 2];
caller.sort((a, b) => a - b);
console.log(caller); // [ 1, 2, 3 ]
Imagine caller belongs to some other part of your app, like a list of scores shown in the order they were entered. If your median function sorts it directly, that list is now reordered, and nothing tells you it happened. A function that only reads data shouldn't change it.
The fix is to sort a copy. slice() with no arguments copies the whole array. Newer JavaScript also has toSorted, which returns a sorted copy directly.
Step 3: the median of an odd-length list
function median(xs) {
const sorted = xs.slice().sort((a, b) => a - b);
const mid = Math.floor(sorted.length / 2);
return sorted[mid];
}
const marks = [72, 88, 61, 95, 79];
console.log(median(marks)); // 79
Sorted, the marks are 61, 72, 79, 88, 95. The length is 5, Math.floor(5 / 2) is 2, and position 2 (counting from 0) holds 79, the middle value.
Step 4: even-length lists
Try it on four values:
console.log(median([1, 2, 3, 4])); // 3
That should be 2.5. With 4 items, mid is 2, which points at the second of the two middle values. For an even count we need the average of positions mid - 1 and mid:
function median(xs) {
const sorted = xs.slice().sort((a, b) => a - b);
const mid = Math.floor(sorted.length / 2);
return sorted.length % 2 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2;
}
console.log(median([1, 2, 3, 4])); // 2.5
console.log(median(wide)); // 170
sorted.length % 2 is 1 for an odd count, which counts as true, so we take the single middle. For an even count it is 0, which counts as false, so we average the pair. For wide, that is (40 + 300) / 2, which is 170.
Step 5: check that the caller's array is safe
const scores = [3, 1, 2];
const answer = median(scores);
console.log(answer); // 2
console.log(scores); // [ 3, 1, 2 ]
The median is 2 and scores is still in its original order.
Step 6: median against mean
const mean = (xs) => xs.reduce((a, b) => a + b, 0) / xs.length;
console.log(median(marks), mean(marks)); // 79 79
console.log(median([...marks, 1000]), mean([...marks, 1000])); // 83.5 232.5
For these five marks, the median and the mean are both 79. Add one wild value of 1000 and the mean leaps to 232.5, while the median only moves to 83.5. To move the median a long way, half the values would have to change. That is why reports on skewed data, like salaries, use it.
Step 7: the edge cases
console.log(median([42])); // 42
console.log(median([])); // NaN
A one-item list is its own median. An empty list has no middle: sorted[-1] + sorted[0] is undefined + undefined, which is NaN. If an empty list can reach your function, decide what it should return and check for it first.
The full solution
The answer panel has median and mean, then prints the default and numeric sorts, the median and mean of the marks, the median of wide, both with an outlier, and the caller's array after the call. Press Run to see the output.
function median(xs) {
const sorted = xs.slice().sort((a, b) => a - b); // slice, or you reorder the caller's array
const mid = Math.floor(sorted.length / 2);
return sorted.length % 2 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2;
}
const marks = [72, 88, 61, 95, 79];
const wide = [5, 40, 300, 1000];
const mean = (xs) => xs.reduce((a, b) => a + b, 0) / xs.length;
const caller = [3, 1, 2];
const answer = median(caller);
console.log('default sort :', wide.slice().sort(), '<- strings');
console.log('numeric sort :', wide.slice().sort((a, b) => a - b));
console.log('median of marks:', median(marks), 'and the mean is', mean(marks));
console.log('median of wide :', median(wide));
console.log('with an outlier:', median([...marks, 1000]), 'against a mean of', mean([...marks, 1000]));
console.log('caller after :', caller, 'answer', answer);
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('a comparator-free sort orders 1000 before 5', wide.slice().sort(), [1000, 300, 40, 5]);
test('and (a, b) => a - b fixes it', wide.slice().sort((a, b) => a - b), [5, 40, 300, 1000]);
test('these five marks have a median of 79, the same as their mean', [median(marks), mean(marks)], [79, 79]);
test('an even count averages the middle pair', [median([1, 2, 3, 4]), median(wide)], [2.5, 170]);
test('one outlier moves the median 4.5 and the mean 153.5', [median([...marks, 1000]), mean([...marks, 1000])], [83.5, 232.5]);
test('the caller\'s array is left in its original order', caller, [3, 1, 2]);
test('a one-element list is its own median', median([42]), 42);
test('and an empty list gives NaN, since there is no middle', Number.isNaN(median([])), true);
Array.prototype.sort converts each element to a string and compares those, so [5, 40, 300, 1000] comes back as [1000, 300, 40, 5]. Every numeric sort needs (a, b) => a - b. It is also in-place, so xs.sort() inside a "read-only" statistics helper quietly reorders whatever the caller passed in; xs.slice() first, or xs.toSorted((a, b) => a - b) where it is available.
The median earns its keep on skewed data. Add a single 1000 to these marks and the median moves from 79 to 83.5 while the mean jumps to 232.5. Half the values have to move before the median does, which is exactly why incomes and house prices are reported as medians.
Common mistakes
- Calling
sort()with no compare function. Numbers are compared as strings, so 1000 comes before 5. Always pass(a, b) => a - b. - Sorting the caller's array.
sortchanges it in place. Copy first withslice(), or usetoSorted. - Forgetting the even case. With an even count there are two middle values. Average them.
Try it yourself
- Find the median of
[7, 3, 9, 1, 5, 8]by hand, then check it with your function. - Write
medianOrNull(xs)that returnsnullfor an empty list. - Change
medianto usetoSortedinstead ofslice().sort(), and check thatscoresis still unchanged.