您可以繼續使用中位數,並讓Math.js爲您排序。
function quartileBounds(_sample){
// find the median as you did
var _median = math.median(_sample)
// split the data by the median
var _firstHalf = _sample.filter(function(f){ return f < _median })
var _secondHalf = _sample.filter(function(f){ return f >= _median })
// find the medians for each split
var _25percent = math.median(_firstHalf);
var _75percent = math.median(_secondHalf);
var _50percent = _median;
var _100percent = math.max(_secondHalf);
// this will be the upper bounds for each quartile
return [_25percent, _50percent, _75percent, _100percent];
}
quartileBounds([7,18,33,32,10,30,77,40,135,30,121,36,26,28,60,80,17,288,114]);
// returns [26,33,78.5,288]