Home > Article > Web Front-end > How Can I Find the Closest Number in an Array to a Given Value?
Finding the Closest Number in an Array
Given a number within a specific range, the goal is to determine the closest number within an array. Let's assume the given number can range from -1000 to 1000.
The Problem:
We have an array of numbers, such as:
[2, 42, 82, 122, 162, 202, 242, 282, 322, 362]
And we want to find the number in the array that is closest to a given value, for example 80.
The Solution: Using the Array.reduce() Method
We can use the Array.reduce() method to solve this problem. The reduce() method applies a reducer function to each element of an array, accumulating the result into a single value.
Here's a JavaScript solution using reduce():
<code class="js">var counts = [2, 42, 82, 122, 162, 202, 242, 282, 322, 362], goal = 80; var closest = counts.reduce(function(prev, curr) { return (Math.abs(curr - goal) < Math.abs(prev - goal) ? curr : prev); }); console.log(closest); // outputs: 82</code>
In this solution, we use the reduce() method to compare the absolute difference between each element of the array and the given number. The element with the smallest absolute difference is assigned to the variable closest.
Finally, we log the value of closest to the console, which in this example would be 82, the closest number to 80 in the array.
The above is the detailed content of How Can I Find the Closest Number in an Array to a Given Value?. For more information, please follow other related articles on the PHP Chinese website!