Skip to content

Files

Latest commit

e35735f · Nov 22, 2024

History

History
26 lines (20 loc) · 798 Bytes

median.md

File metadata and controls

26 lines (20 loc) · 798 Bytes
标题 标签
median(获取数字数组的中位数) math,array(数学,数组)

计算数字数组的中位数

  • 找到数组的中间位置,使用 Array.prototype.sort() 对值进行排序。
  • 如果 Array.prototype.length 为奇数,则返回中点的数字,否则返回中间两个数字的平均值。
const median = (arr) => {
  const mid = Math.floor(arr.length / 2),
    newArr = arr.sort((a, b) => a - b);
  return arr.length % 2 !== 0
    ? newArr[mid]
    : (newArr[mid - 1] + newArr[mid]) / 2;
};

调用方式:

median([5, 6, 50, 1, -5]); // 5

应用场景