Calculating median - javascript

后端 未结 9 830
轮回少年
轮回少年 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:17

    Short and sweet.

    Array.prototype.median = function () {
      return this.slice().sort((a, b) => a - b)[Math.floor(this.length / 2)]; 
    };
    

    Usage

    [4, 5, 7, 1, 33].median()
    

    Works with strings as well

    ["a","a","b","b","c","d","e"].median()
    

提交回复
热议问题