Skip to content

Instantly share code, notes, and snippets.

@caseyjustus
Created August 23, 2011 19:34
Show Gist options
  • Select an option

  • Save caseyjustus/1166258 to your computer and use it in GitHub Desktop.

Select an option

Save caseyjustus/1166258 to your computer and use it in GitHub Desktop.
calculate the median of an array with javascript
function median(values) {
values.sort( function(a,b) {return a - b;} );
var half = Math.floor(values.length/2);
if(values.length % 2)
return values[half];
else
return (values[half-1] + values[half]) / 2.0;
}
var list1 = [3, 8, 9, 1, 5, 7, 9, 21];
median(list1);
@danielbayerlein
Copy link
Copy Markdown

@sqren Thank you for the explanation.

@sorenlouv
Copy link
Copy Markdown

@danielbayerlein You are welcome.
Btw. Noticed your project https://github.com/danielbayerlein/git-pick. I've create a tool called backport: https://github.com/sqren/backport

Looks like we are doing something similar :D

@primegurjar
Copy link
Copy Markdown

I would also check the length first. if it is zero return. no need to proceed further.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment