Created
July 22, 2018 20:10
-
-
Save kebman/6ef8c75c2895c2e3f20274cb08c235a6 to your computer and use it in GitHub Desktop.
Find the median of an array of numbers using JavaScript
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(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