Closest numeric match

Angelos Chalaris · JavaScript, Math, Array · Mar 30, 2022

Finds the closest number from an array.

  • Use Array.prototype.reduce() to scan all elements of the array.
  • Use Math.abs() to compare each element's distance from the target value, storing the closest match.
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

Would you like to help us improve 30 seconds of code?Take a quick survey

Recommended snippets

  • Calculates the product of two or more numbers/arrays.

  • Standard deviation

    JavaScript, Math

    Calculates the standard deviation of an array of numbers.

  • Percentile of matches

    JavaScript, Math

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