Skip to content

Instantly share code, notes, and snippets.

@rmeissn
Last active July 20, 2021 12:13
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save rmeissn/f5b42fb3e1386a46f60304a57b6d215a to your computer and use it in GitHub Desktop.
Save rmeissn/f5b42fb3e1386a46f60304a57b6d215a 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));
}
@chauhansaurabhb
Copy link

Thanks for sharing a useful piece of code.

@DeathInWhite
Copy link

This is awesome! thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment