findClosestNumber.tsx 359 B

12345678910
  1. /**
  2. * Finds the closest match to the number from the provided numbers array
  3. */
  4. export function findClosestNumber(number: number, numbersArray: number[]) {
  5. return numbersArray.reduce((previousBest: number, currentNumber) => {
  6. return Math.abs(currentNumber - number) < Math.abs(previousBest - number)
  7. ? currentNumber
  8. : previousBest;
  9. });
  10. }