Created
April 1, 2014 19:43
-
-
Save webinista/9921572 to your computer and use it in GitHub Desktop.
A simple function for finding the median value in an array of numbers.
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
var median = function(array){ | |
var med, a, len; | |
len = array.length; | |
/* Sort by numeric value */ | |
a = array.sort(function(a,b){return a - b}); | |
med = Math.floor(len / 2); | |
/* | |
If we have an odd number of items, take the one at the mid point. | |
Otherwise find the middle two and find the mean. | |
*/ | |
if( len % 2 ){ | |
return array[med]; | |
} else { | |
var mid_a = len / 2; | |
med = array[len / 2] + array[ (len/2) - 1]; | |
return med / 2; | |
} | |
} | |
/* Example usage */ | |
median([2,3,5,6,7,8,9,0]); // 5.5 | |
median([2,3,5]); // 3 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment