Calculating median - javascript

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

    Simple solution:

    function calcMedian(array) {
      const {
        length
      } = array;
    
      if (length < 1)
        return 0;
    
      //sort array asc
      array.sort((a, b) => a - b);
    
      if (length % 2) {
        //length of array is odd
        return array[(length + 1) / 2 - 1];
      } else {
        //length of array is even
        return 0.5 * [(array[length / 2 - 1] + array[length / 2])];
      }
    }
    
    console.log(2, calcMedian([1, 2, 2, 5, 6]));
    console.log(3.5, calcMedian([1, 2, 2, 5, 6, 7]));
    console.log(9, calcMedian([13, 9, 8, 15, 7]));
    console.log(3.5, calcMedian([1, 4, 6, 3]));
    console.log(5, calcMedian([5, 1, 11, 2, 8]));

提交回复
热议问题