JSFiddle - React, Tailwind, and code Playground

by coktopus

JavaScript

// cons - inconsistent result on small samples(100 not 1000)
// pros - can handle any random number of samples

let arr = [];
let a = 0;

while(a<100){ //change this to 1000
  arr.push(a)
  a++
};


const targetValue = 10;

let closestValue = null
let closestValueIndex = -1

const closest = arr.reduce((a, b) => {
    return Math.abs(b - targetValue) < Math.abs(a - targetValue) ? b : a;
});

  
console.log('prob. to exceed', (1-arr.indexOf(closest)/arr.length)*100, 
arr.indexOf(closest)/arr.length, 
arr.length
)