Skip to content

Instantly share code, notes, and snippets.

@ogun
Forked from rmeissn/outliersFilter.js
Created September 3, 2017 15:08
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save ogun/f19dc055e6b84d57e8186cbc9eaa8e45 to your computer and use it in GitHub Desktop.
Save ogun/f19dc055e6b84d57e8186cbc9eaa8e45 to your computer and use it in GitHub Desktop.
A Javascript function to filter an array of values for outliers by using an interquartile filter
function filterOutliers(someArray) {
if(someArray.length < 4)
return someArray;
let values, q1, q3, iqr, maxValue, minValue;
values = someArray.slice().sort( (a, b) => a - b);//copy array fast and sort
if((values.length / 4) % 1 === 0){//find quartiles
q1 = 1/2 * (values[(values.length / 4)] + values[(values.length / 4) + 1]);
q3 = 1/2 * (values[(values.length * (3 / 4))] + values[(values.length * (3 / 4)) + 1]);
} else {
q1 = values[Math.floor(values.length / 4 + 1)];
q3 = values[Math.ceil(values.length * (3 / 4) + 1)];
}
iqr = q3 - q1;
maxValue = q3 + iqr * 1.5;
minValue = q1 - iqr * 1.5;
return values.filter((x) => (x >= minValue) && (x <= maxValue));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment