Problems › JavaScript › patterns
The middle of the list
A dashboard shows a campaign’s typical daily spend, and “typical” is whatever lands in the middle once the days are sorted.
- An odd number of readings: the middle one, once sorted.
- An even number: the average of the two middle ones.
- An empty list has no middle: return zero.
medianOf(values: list<int>) → float
Where you start
function medianOf(values) {
}
Worked examples
| Call | Result |
|---|---|
medianOf([3,1,2]) | 2 |
medianOf([1,2]) | 1.5 |
medianOf([5]) | 5 |
medianOf([5,1,4,2]) | 3 |
Hint
Sort a copy, not the caller’s list, then look at the middle pair or single value.
Reference solution in JavaScript
function medianOf(values) {
const xs = values.slice().sort((a, b) => a - b);
const n = xs.length;
if (n === 0) return 0;
const mid = Math.floor(n / 2);
return n % 2 === 1 ? xs[mid] : (xs[mid - 1] + xs[mid]) / 2;
}