Home > Article > Web Front-end > How to Find the Nearest Number in an Array Using JavaScript?
Finding the Nearest Number in an Array
Given an array of numbers, a task often arises to find the closest number to a given target value. Consider an example where the target number is 80 and the array contains [2, 42, 82, 122, 162, 202, 242, 282, 322, 362]. The closest number to 80 in this array is 82.
ES5 JavaScript Solution:
<code class="javascript">var counts = [4, 9, 15, 6, 2], goal = 5; var closest = counts.reduce(function(prev, curr) { return (Math.abs(curr - goal) < Math.abs(prev - goal) ? curr : prev); }); console.log(closest); // Output: 6</code>
In this solution, the reduce() method is used to iterate over each element in the counts array and compare its absolute difference with the target value goal. The smallest absolute difference determines the closest number, which is then returned as the closest variable.
The above is the detailed content of How to Find the Nearest Number in an Array Using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!