计算数组JavaScript的中位数
我们需要编写一个JavaScript函数,该函数接受Numbers数组并返回其中位数。
中位数的统计意义
中位数是排序的数字列表(升序或降序)中的中间数字,并且比平均值更能说明该数据集。
方法
首先,我们将对数组进行排序,如果数组的大小为偶数,我们将需要额外的逻辑来处理两个中间数字。
在这些情况下,我们将需要返回这两个数字的平均值。
示例
const arr = [4, 6, 2, 45, 2, 78, 5, 89, 34, 6];
const findMedian = (arr = []) => {
const sorted = arr.slice().sort((a, b) => {
return a - b;
});
if(sorted.length % 2 === 0){
const first = sorted[sorted.length / 2 - 1];
const second = sorted[sorted.length / 2];
return (first + second) / 2;
}
else{
const mid = Math.floor(sorted.length / 2);
return sorted[mid];
};
};
console.log(findMedian(arr));输出结果
控制台中的输出将是-
6
热门推荐
10 财运虎年祝福语简短语
11 单亲爸爸春节祝福语简短
12 狗狗上厕所训练
13 植物种植祝福语简短
14 翻译考试祝福语朋友简短
15 个人周年庆简短祝福语
16 狗狗怎么训练
17 分别祝福语简短搞笑英文
18 生日广州男生祝福语简短