计算数组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 妈妈生日祝福语简短励志