Skip to content

Instantly share code, notes, and snippets.

@cheeaun
Created June 14, 2020 07:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cheeaun/2213b52fa3e308454bcd720a9c6999bc to your computer and use it in GitHub Desktop.
Save cheeaun/2213b52fa3e308454bcd720a9c6999bc to your computer and use it in GitHub Desktop.
Find median from array of numbers (mutable, due to .sort())
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