Skip to content

Instantly share code, notes, and snippets.

@tregoning
Created March 18, 2019 17:02
Show Gist options
  • Save tregoning/43cff60f606f50e1f4d556a346be16bb to your computer and use it in GitHub Desktop.
Save tregoning/43cff60f606f50e1f4d556a346be16bb to your computer and use it in GitHub Desktop.
percentileOfScore similar to Python's scipy.stats.percentileofscore(kind='mean') - #js #javascript #stats #percentile
/**
* @see [https://en.wikipedia.org/wiki/Percentile_rank]
* @param {array} data - list of values
* @param {number } value - value that we need fo find percentile rank for
* @returns {number} - returns the percentile rank/score for the provided value
*/
export const percentileOfScore = (data, value) => {
if (!data.length) {
throw new Error('Data array is empty');
}
// sorting array in place
data.sort();
let lowerCount = 0;
let sameCount = 0;
for (let i = 0; i < data.length; i++) {
if (data[i] < value) {
lowerCount++;
} else if (data[i] === value) {
sameCount++;
} else {
break;
}
}
return (lowerCount + 0.5 * sameCount) / data.length * 100;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment