Calculating median - javascript

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

    TypeScript Answer 2020:

    // Calculate Median 
    const calculateMedian = (array: Array) => {
      // Check If Data Exists
      if (array.length >= 1) {
        // Sort Array
        array = array.sort((a: number, b: number) => {
          return a - b;
        });
    
        // Array Length: Even
        if (array.length % 2 === 0) {
          // Average Of Two Middle Numbers
          return (array[(array.length / 2) - 1] + array[array.length / 2]) / 2;
        }
        // Array Length: Odd
        else {
          // Middle Number
          return array[(array.length - 1) / 2];
        }
      }
      else {
        // Error
        console.error('Error: Empty Array (calculateMedian)');
      }
    };
    
    

提交回复
热议问题