Home >Web Front-end >JS Tutorial >How to Find the Nearest Number in an Array to a Given Value?

How to Find the Nearest Number in an Array to a Given Value?

Linda Hamilton
Linda HamiltonOriginal
2024-11-03 12:30:02225browse

How to Find the Nearest Number in an Array to a Given Value?

Determining the Nearest Number in an Array

Suppose you have a numerical value ranging from -1000 to 1000 and an array containing integers, such as:

[2, 42, 82, 122, 162, 202, 242, 282, 322, 362]

Your task is to modify the given number to match the closest number from the array. For instance, if your given number is 80, it should be adjusted to 82.

Solution:

To achieve the desired result, we can leverage the reduce() method to find the closest number in the array to our target number. The reduce() method takes a function and an initial accumulator value as its arguments, iterating through the array and applying the function to each element and the accumulator.

Here's an example implementation in ES5 JavaScript:

<code class="js">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 example, the reduce() method calculates the absolute difference between each array element and the target number (5). It then compares the absolute differences and assigns the element with the smallest difference to the closest variable. The closest variable holds the value 6, which is the nearest number to 5 in the array.

The above is the detailed content of How to Find the Nearest Number in an Array to a Given Value?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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