Skip to content

Instantly share code, notes, and snippets.

@nishinoshake
Last active December 1, 2016 11:11
Show Gist options
  • Save nishinoshake/c90bf69d466c00506e85 to your computer and use it in GitHub Desktop.
Save nishinoshake/c90bf69d466c00506e85 to your computer and use it in GitHub Desktop.
JSで中央値を計算する
var getMedian = function(arr) {
var half = Math.floor(arr.length / 2);
var temp = arr.sort(function(a, b) { return a - b; });
console.log(temp);
if ( temp.length % 2 ) {
return temp[half];
} else {
return ( temp[half - 1] + temp[half] ) / 2;
}
};
console.log(median([1, 2, 3, 4, 5])); // 3
console.log(median([1, 2, 3, 4, 5, 6])); // 3.5
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment