Skip to content

Instantly share code, notes, and snippets.

@kebman
Created July 22, 2018 20:10
Show Gist options
  • Save kebman/6ef8c75c2895c2e3f20274cb08c235a6 to your computer and use it in GitHub Desktop.
Save kebman/6ef8c75c2895c2e3f20274cb08c235a6 to your computer and use it in GitHub Desktop.
Find the median of an array of numbers using JavaScript
function median(arr) {
let middle = Math.floor((arr.length-1)/2);
if (arr.length % 2) {
return arr[middle]; // odd
} else {
return (arr[middle]+arr[middle+1])/2; // even
}
}
// test
const odd = [1,2,3,4,5];
const even = [1,2,3,4,5,6];
console.log(median(even));
// some neat helper functions
// sum the array - neat when looking for the average
function sumArr(arr) {
return arr.reduce((a, b) => a + b, 0);
}
// sort the array - neat before applying median()
function sortArr(arr) {
return arr.sort((a, b) => a - b);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment