Skip to content

Instantly share code, notes, and snippets.

@namcoder
Forked from caseyjustus/median.js
Created August 30, 2018 04:19
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 namcoder/cf59e4c611828bd2af20a19f78fc014a to your computer and use it in GitHub Desktop.
Save namcoder/cf59e4c611828bd2af20a19f78fc014a 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);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment