Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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);
- }
Add Comment
Please, Sign In to add comment