Home > Web Front-end > JS Tutorial > body text

How Can I Find the Closest Number in an Array to a Given Value?

Patricia Arquette
Release: 2024-10-30 17:52:31
Original
604 people have browsed it

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]
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!