Skip to content

Instantly share code, notes, and snippets.

@webinista
Created April 1, 2014 19:43
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 webinista/9921572 to your computer and use it in GitHub Desktop.
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.
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