Calculating median - javascript

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

    Here's another solution:

    function median(numbers) {
        const sorted = numbers.slice().sort((a, b) => a - b);
        const middle = Math.floor(sorted.length / 2);
    
        if (sorted.length % 2 === 0) {
            return (sorted[middle - 1] + sorted[middle]) / 2;
        }
    
        return sorted[middle];
    }
    
    console.log(median([4, 5, 7, 1, 33]));

提交回复
热议问题