30秒学会 JavaScript 片段 · 2022年12月7日

30秒学会 JavaScript 片段 – Closest numeric match

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

翻译自:https://www.30secondsofcode.org/js/s/closest-numeric-match