Emmanuel Akinfulubi

JavaScriptMath

Calculate percentiles in JavaScript

Advanced · 5 min read

"You scored in the 90th percentile" means you did better than about 90% of the people who took the test. A percentile is a value that a given share of the data sits below. The 50th percentile is the median, and the 25th and 75th are the quartiles you see on a box plot.

Percentiles show up in exam results, baby growth charts, salary surveys and website speed reports ("95% of pages load in under 412 ms"). In this tutorial you will write two percentile functions, see them give different answers for the same list, and learn why both can be right. You need to know arrays, sort and Math.floor / Math.ceil.

There is more than one definition

This surprises most people: there is no single agreed way to compute a percentile. Statistics books list several methods, and on a small list they can disagree by a whole element. We will build the two most common ones.

  • Nearest rank sorts the list and picks one of the actual values. The answer is always a number that was in your data.
  • Linear interpolation works out a position that can fall between two values, then takes the point that far along the gap between them. The answer can be a number nobody scored.

Sorting numbers properly

Both methods start by sorting. In JavaScript, sort() with no argument compares values as text, so [10, 9] stays [10, 9]. Pass a compare function to sort numbers:

JavaScript

console.log([10, 9, 100].sort());                 // [ 10, 100, 9 ]
console.log([10, 9, 100].sort((x, y) => x - y));  // [ 9, 10, 100 ]

sort also changes the array it is called on. Calling xs.slice() first makes a copy, so the caller's list is left alone.

Here is the exercise. Try it on your own first if you like, then read on and we will build it together.

61 Percentiles, on a stated definition

hard

Compute the 30th percentile of [15, 20, 35, 40, 50] two ways: nearest rank, and linear interpolation between neighbours. Get different answers, then show both agree at the median and at the extremes.

Stuck? Three hints, smallest first
  1. 1. Nearest rank: sort, take Math.ceil(p / 100 * n) and index that, 1-based.
  2. 2. Interpolated: the position is (n - 1) * p / 100, which usually lands between two elements.
  3. 3. Every definition must agree at p=0, p=50 for an odd count, and p=100. They are free to differ everywhere else.

Step 1: nearest rank

Take the scores 15, 20, 35, 40 and 50. For the 30th percentile, nearest rank asks: "what is 30% of 5 items?" That is 1.5. Round it up to 2, and take the 2nd value, counting from 1.

Step 1

function nearestRank(xs, p) {
  const a = xs.slice().sort((x, y) => x - y);
  if (p <= 0) return a[0];
  const rank = Math.ceil((p / 100) * a.length);        // 1-based
  return a[Math.min(rank, a.length) - 1];
}
const scores = [15, 20, 35, 40, 50];
console.log(nearestRank(scores, 30)); // 20

The rank counts from 1, but array indexes count from 0, so we subtract 1. Two guards keep the index inside the array: p <= 0 returns the smallest value (a rank of 0 would mean index -1), and Math.min(rank, a.length) stops a percentile above 100 from running off the end.

Step 2: linear interpolation

Interpolation thinks of the sorted values as standing on positions 0 to 4. The 30th percentile sits 30% of the way along, at position (5 - 1) * 30 / 100, which is 1.2.

Position 1.2 is between index 1 (the value 20) and index 2 (the value 35). It is 0.2 of the way across that gap of 15, so the answer is 20 + 0.2 × 15 = 23.

Step 2

function interpolated(xs, p) {
  const a = xs.slice().sort((x, y) => x - y);
  const i = ((a.length - 1) * p) / 100;                // 0-based, fractional
  const lo = Math.floor(i);
  const hi = Math.ceil(i);
  return lo === hi ? a[lo] : a[lo] + (i - lo) * (a[hi] - a[lo]);
}
console.log(interpolated(scores, 30)); // 23

Math.floor and Math.ceil give the index on each side. When the position is a whole number, lo and hi are equal and we just return that value.

Step 3: put them side by side

A small helper runs both methods at once, so it is easy to compare.

Step 3

const both = (p) => [nearestRank(scores, p), interpolated(scores, p)];
console.log(both(30)); // [ 20, 23 ]
console.log(both(40)); // [ 20, 29 ]

Same list, same question, two answers. Neither is a bug. They are two different definitions, and a percentile function should say which one it uses.

Step 4: where every method agrees

There are fixed points that any sensible definition must agree on: the smallest value at p = 0, the largest at p = 100, and the median at p = 50 when the list has an odd number of values.

Step 4

console.log(both(50));            // [ 35, 35 ]
console.log(both(0), both(100));  // [ 15, 15 ] [ 50, 50 ]

Both give 35, the middle score, at p = 50. Both give 15 and 50 at the ends. Everywhere else, they are free to differ.

Step 5: quartiles and values nobody scored

The quartiles are the 25th and 75th percentiles. The gap between them, the interquartile range (IQR), tells you how spread out the middle half of the data is.

Step 5

const q1 = interpolated(scores, 25);
const q3 = interpolated(scores, 75);
console.log(q1, q3, q3 - q1);           // 20 40 20
console.log(interpolated(scores, 35));  // 26
console.log(scores.includes(26));       // false

Interpolation at p = 35 returns 26, which is nobody's score. That is fine for a box plot. But for "the 90th percentile response time was 412 ms" you usually want a time that really happened, and nearest rank always gives you one.

Step 6: an even count and a single value

With four values there is no middle one. Interpolation lands halfway between the two middle values, which is exactly the median you already know:

Step 6

console.log(interpolated([1, 2, 3, 4], 50));          // 2.5
console.log(nearestRank([42], 17), interpolated([42], 17)); // 42 42

With only one value, every percentile is that value, and both methods agree.

The full solution

The answer panel has both functions, compares them at the 30th, 40th and 50th percentiles and at the ends, and prints the quartiles, the IQR, the 35th percentile and the even-count case. Press Run to see the output.

The answer

function nearestRank(xs, p) {
  const a = xs.slice().sort((x, y) => x - y);
  if (p <= 0) return a[0];
  const rank = Math.ceil((p / 100) * a.length);        // 1-based
  return a[Math.min(rank, a.length) - 1];
}

function interpolated(xs, p) {
  const a = xs.slice().sort((x, y) => x - y);
  const i = ((a.length - 1) * p) / 100;                // 0-based, fractional
  const lo = Math.floor(i);
  const hi = Math.ceil(i);
  return lo === hi ? a[lo] : a[lo] + (i - lo) * (a[hi] - a[lo]);
}

const scores = [15, 20, 35, 40, 50];
const both = (p) => [nearestRank(scores, p), interpolated(scores, p)];

const q1 = interpolated(scores, 25);
const q3 = interpolated(scores, 75);

console.log('p30 :', both(30), '<- the two definitions disagree');
console.log('p40 :', both(40));
console.log('p50 :', both(50), 'and the median is 35');
console.log('p0, p100:', both(0), both(100));
console.log('quartiles:', q1, q3, 'IQR', q3 - q1);
console.log('p35 :', interpolated(scores, 35));
console.log('even count, p50:', interpolated([1, 2, 3, 4], 50));

Output


      
9 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 9 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

9 checks

test('at the 30th percentile nearest rank says 20 and interpolation says 23', both(30), [20, 23]);
test('and at the 40th they say 20 and 29', both(40), [20, 29]);
test('both agree at the median of an odd-length list', both(50), [35, 35]);
test('and at the two ends', [both(0), both(100)], [[15, 15], [50, 50]]);
test('the interpolated quartiles are 20 and 40, so the IQR is 20', [q1, q3, q3 - q1], [20, 40, 20]);
test('interpolation at p50 of an even count is the median again', interpolated([1, 2, 3, 4], 50), 2.5);
test('nearest rank always returns a value that was in the list', scores.includes(nearestRank(scores, 35)), true);
test('interpolation need not: p35 is 26, which is nobody\'s score', [interpolated(scores, 35), scores.includes(26)], [26, false]);
test('with one value, every percentile is that value', [nearestRank([42], 17), interpolated([42], 17)], [42, 42]);

There is no single definition of a percentile. One statistics text lists nine, and they disagree by a whole element on small samples: here the 30th percentile is 20 or 23 depending on which you picked. Neither is wrong; a function that does not say which it implements is. The three fixed points are p=0, p=100 and — for an odd count — p=50, and any two definitions that disagree there are not both percentiles.

The practical difference is whether the answer has to be a real observation. Nearest rank always returns one of your data points, which is what you want for "the 90th percentile response time was 412ms". Interpolation returns a number between two of them, which is what a box plot's quartiles need, and it is what PERCENTILE.INC in a spreadsheet and numpy.percentile do by default. Interpolated results are also plain floating-point arithmetic, so round before printing: the values here came out exact only because the gaps happened to be tidy.

Common mistakes

  • Forgetting to sort numerically. sort() without a compare function sorts as text, and the percentile comes out of the wrong place.
  • Mixing up 1-based and 0-based. A rank of 2 is index 1. Forgetting the - 1 gives you the next value up.
  • Not saying which definition you used. Spreadsheets and data libraries do not all use the same method, so your numbers may not match theirs unless you name the method.

Try it yourself

  1. Find the 90th percentile of [412, 120, 95, 300, 150, 210, 180, 99, 130, 160] with both functions.
  2. Change interpolated so it throws a RangeError when p is below 0 or above 100.
  3. Write iqr(xs) that returns the interquartile range of any list, and try it on [1, 2, 3, 4, 5, 6, 7, 8].

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.