How to get median and quartiles/percentiles of an array in JavaScript (or PHP)?

前端 未结 3 1174
我寻月下人不归
我寻月下人不归 2021-02-07 06:24

This question is turned into a Q&A, because I had struggle finding the answer, and think it can be useful for others

I have a JavaScript

3条回答
  •  孤城傲影
    2021-02-07 06:46

    I updated the JavaScript translation from the first answer to use arrow functions and a bit more concise notation. The functionality remains mostly the same, except for std, which now computes the sample standard deviation (dividing by arr.length - 1 instead of just arr.length)

    // sort array ascending
    const asc = arr => arr.sort((a, b) => a - b);
    
    const sum = arr => arr.reduce((a, b) => a + b, 0);
    
    const mean = arr => sum(arr) / arr.length;
    
    // sample standard deviation
    const std = (arr) => {
        const mu = mean(arr);
        const diffArr = arr.map(a => (a - mu) ** 2);
        return Math.sqrt(sum(diffArr) / (arr.length - 1));
    };
    
    const quantile = (arr, q) => {
        const sorted = asc(arr);
        const pos = (sorted.length - 1) * q;
        const base = Math.floor(pos);
        const rest = pos - base;
        if (sorted[base + 1] !== undefined) {
            return sorted[base] + rest * (sorted[base + 1] - sorted[base]);
        } else {
            return sorted[base];
        }
    };
    
    const q25 = arr => quantile(arr, .25);
    
    const q50 = arr => quantile(arr, .50);
    
    const q75 = arr => quantile(arr, .75);
    
    const median = arr => q50(arr);
    

提交回复
热议问题