Files
30-seconds-of-code/snippets/js/s/closest.md
2023-05-10 22:35:09 +03:00

548 B

title, type, language, tags, author, cover, dateModified
title type language tags author cover dateModified
Closest numeric match snippet javascript
math
chalarangelo green-cabin-cow 2022-03-30T05:00:00-04:00

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