Files
reference/note/javascript/array/find-the-closest-number-from-an-array.md
T
2022-10-18 11:37:51 +08:00

832 B

title, tags, layout
title tags layout
How to find the closest number from an array in JavaScript
JavaScript
ES6
one-line
js
Array
note

In this Article we will go through how to find the closest number from an array only using single line of code in JavaScript. This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => Arrow Function.

Let's define this short function:

// Find the number from `arr` which is closest to `n`
const closest = (arr, n) => arr.reduce((prev, curr) => Math.abs(curr - n) < Math.abs(prev - n) ? curr : prev);

Or

const closest = (arr, n) => arr.sort((a, b) => Math.abs(a - n) - Math.abs(b - n))[0];

Example

closest([29, 87, 8, 78, 97, 20, 75, 33, 24, 17], 50);   // 33