Last active
December 1, 2016 11:11
-
-
Save nishinoshake/c90bf69d466c00506e85 to your computer and use it in GitHub Desktop.
JSで中央値を計算する
This file contains hidden or 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 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