我们需要编写一个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