Closest numeric match

JavaScript, Math · Mar 30, 2022

Finds the closest number from an array.

const closest = (arr, n) =>
  arr.reduce((acc, num) => (Math.abs(num - n) < Math.abs(acc - n) ? num : acc));

closest([6, 1, 3, 7, 9], 5); // 6

More like this

  • Product of numeric values

    Calculates the product of two or more numbers/arrays.

    JavaScript, Math · Oct 22, 2020

  • Percentile of matches

    Calculates the percentage of numbers in the given array that are less or equal to the given value.

    JavaScript, Math · Oct 22, 2020

  • Digitize number

    Converts a number to an array of digits, removing its sign if necessary.

    JavaScript, Math · Oct 18, 2020