从数据 0,1,2,2,2,3,111,2,333,4,3,2
中找到 111
和 333
这两个异常值
const outlierDetector = (collection) => {
const size = collection.length;
let q1, q3;
if (size < 2) {
return collection;
}
const sortedCollection = collection.slice().sort((a, b) => a - b);
if (((size - 1) / 4) % 1 === 0 || (size / 4) % 1 === 0) {
q1 =
(1 / 2) *
(sortedCollection[Math.floor(size / 4) - 1] +
sortedCollection[Math.floor(size / 4)]);
q3 =
(1 / 2) *
(sortedCollection[Math.ceil((size * 3) / 4) - 1] +
sortedCollection[Math.ceil((size * 3) / 4)]);
} else {
q1 = sortedCollection[Math.floor(size / 4)];
q3 = sortedCollection[Math.floor((size * 3) / 4)];
}
const iqr = q3 - q1;
const maxValue = q3 + iqr * 1.5;
return sortedCollection.filter((value) => value >= maxValue);
};
let a = [1,2,3,1,2,111,22,2,1,2]
let b = [1,4,7,20,3,5,12,33]
let c = [1,4,7,20,3,5,12,33,50,100]
outlierDetector(a);
outlierDetector(b);
outlierDetector(c);