Median of numbers in JavaScript
The middle value, which needs a sort and a decision about even-length input.
function median(numbers) {
const sorted = [...numbers].sort((a, b) => a - b);
const mid = Math.floor(sorted.length / 2);
return sorted.length % 2
? sorted[mid]
: (sorted[mid - 1] + sorted[mid]) / 2;
}
Keywords and builtins used here
Mathconstfunctionreturn
The run, in numbers
- Lines
- 7
- Characters to type
- 200
- Tokens
- 70
- Three-star pace
- 90 tpm
At the three-star pace of 90 tokens a minute, this run takes about 47 seconds.
Step 9 of 10 in Arrays, step 25 of 43 in Language basics.