[removed] remove outlier from an array?

前端 未结 5 1625
-上瘾入骨i
-上瘾入骨i 2021-01-02 03:10
values = [8160,8160,6160,22684,0,0,60720,1380,1380,57128]

how can I remove outliers like 0, 57218, 60720 and 22684?

Is there a library whic

5条回答
  •  庸人自扰
    2021-01-02 03:53

    I had some problems with the other two solutions. Problems like having NaN values as q1 and q3 because of wrong indexes. The array length needs to have an -1 because of the 0 index. Then it is checked if the index is a int or decimal, in the case of a decimal the value between two indexes is extracted.

    function filterOutliers (someArray) {
        if (someArray.length < 4) {
            return someArray;
        }
    
        let values = someArray.slice().sort((a, b) => a - b); // copy array fast and sort
    
        let q1 = getQuantile(values, 25);
        let q3 = getQuantile(values, 75);
    
        let iqr, maxValue, minValue;
        iqr = q3 - q1;
        maxValue = q3 + iqr * 1.5;
        minValue = q1 - iqr * 1.5;
    
        return values.filter((x) => (x >= minValue) && (x <= maxValue));
    }
    
    function getQuantile (array, quantile) {
        // Get the index the quantile is at.
        let index = quantile / 100.0 * (array.length - 1);
    
        // Check if it has decimal places.
        if (index % 1 === 0) {
            return array[index];
        } else {
            // Get the lower index.
            let lowerIndex = Math.floor(index);
            // Get the remaining.
            let remainder = index - lowerIndex;
            // Add the remaining to the lowerindex value.
            return array[lowerIndex] + remainder * (array[lowerIndex + 1] - array[lowerIndex]);
        }
    }
    

提交回复
热议问题