find the 99th percentile in javascript

To find the 99th percentile, we need to sort the data and then identify the value at the threshold position. To do this in JavaScript, we can follow these steps:

  1. Sort the array of data in ascending order
  2. Determine the percentile threshold position by multiplying the length of the array by the percentile we want, then divide by 100. For example, for the 99th percentile of an array of 1000 values, the threshold position would be 990 (1000 * 0.99).
  3. Round the threshold position up to the nearest whole number, as percentile positions are whole numbers
  4. Return the value in the array at the threshold position

Here's the JavaScript code:

index.tsx
function findPercentile(data, percentile) {
  // Step 1: sort the data in ascending order
  data.sort(function(a, b) {
    return a - b;
  });

  // Step 2: calculate the position of the percentile threshold
  var thresholdPosition = Math.ceil(data.length * percentile / 100);

  // Step 3: return the value at the threshold position
  return data[thresholdPosition - 1];
}

// Example usage
var myArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var myPercentile = 99;
var myResult = findPercentile(myArray, myPercentile); // returns 10
530 chars
18 lines

gistlibby LogSnag