Skip to content

Instantly share code, notes, and snippets.

@lagner
Forked from IceCreamYou/percentile.js
Created May 16, 2016 18:23
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lagner/6c7bdbbb29fceda1b3b9c5c463b15df4 to your computer and use it in GitHub Desktop.
Save lagner/6c7bdbbb29fceda1b3b9c5c463b15df4 to your computer and use it in GitHub Desktop.
Utility functions to calculate percentiles and percent ranks in a JavaScript array.
// Returns the value at a given percentile in a sorted numeric array.
// "Linear interpolation between closest ranks" method
function percentile(arr, p) {
if (arr.length === 0) return 0;
if (typeof p !== 'number') throw new TypeError('p must be a number');
if (p <= 0) return arr[0];
if (p >= 1) return arr[arr.length - 1];
var index = arr.length * p,
lower = Math.floor(index),
upper = lower + 1,
weight = index % 1;
if (upper >= arr.length) return arr[lower];
return arr[lower] * (1 - weight) + arr[upper] * weight;
}
// Returns the percentile of the given value in a sorted numeric array.
function percentRank(arr, v) {
if (typeof v !== 'number') throw new TypeError('v must be a number');
for (var i = 0, l = arr.length; i < l; i++) {
if (v <= arr[i]) {
while (i < l && v === arr[i]) i++;
if (i === 0) return 0;
if (v !== arr[i-1]) {
i += (v - arr[i-1]) / (arr[i] - arr[i-1]);
}
return i / l;
}
}
return 1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment