Created
June 14, 2020 07:11
-
-
Save cheeaun/2213b52fa3e308454bcd720a9c6999bc to your computer and use it in GitHub Desktop.
Find median from array of numbers (mutable, due to .sort())
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function median(numbers) { | |
const middle = (numbers.length + 1) / 2; | |
const sorted = numbers.sort((a, b) => a - b); | |
const isEven = sorted.length % 2 === 0; | |
return isEven | |
? (sorted[middle - 1.5] + sorted[middle - 0.5]) / 2 | |
: sorted[middle - 1]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment