Calculate Percentile

Calculate the nth percentile of an array using linear interpolation.

Code

General
const sorted = [...arr].sort((a, b) => a - b);
const index = (p / 100) * (sorted.length - 1);
const lower = Math.floor(index);
const fraction = index - lower;
return sorted[lower] + fraction * (sorted[lower + 1] - sorted[lower] || 0);

Parameters

Array of numbers

Percentile (0-100)

Browser·fetch() may be limited by CORS

More JavaScript Snippets