Calculating median - javascript

后端 未结 9 845
轮回少年
轮回少年 2021-02-12 09:39

I\'ve been trying to calculate median but still I\'ve got some mathematical issues I guess as I couldn\'t get the correct median value and couldn\'t figure out

9条回答
  •  臣服心动
    2021-02-12 10:08

    Simpler & more efficient

    const median = dataSet => {
      if (dataSet.length === 1) return dataSet[0]
      const sorted = ([ ...dataSet ]).sort()
      const ceil = Math.ceil(sorted.length / 2)
      const floor = Math.floor(sorted.length / 2)
      if (ceil === floor) return sorted[floor]
      return ((sorted[ceil] + sorted[floor]) / 2)
    }
    

提交回复
热议问题