计算数组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
热门推荐
1 带狗狗训练
4 听力训练狗狗
6 怎训练狗狗
7 腹肌训练狗狗
8 网球训练狗狗
9 记叙文训练狗狗
10 狗狗太凶怎么训练
11 核心力量训练狗狗
12 狗狗乱叫怎么训练
13 发音训练狗狗
14 怎么训练狗狗叼东西给主人
15 荆州训练狗狗
16 篮球训练狗狗
17 做训练狗狗
18 训练狗狗坐姿