Home > Web Front-end > JS Tutorial > How to Find the Nearest Number in an Array Using the Reduce Function?

How to Find the Nearest Number in an Array Using the Reduce Function?

Mary-Kate Olsen
Release: 2024-10-30 06:02:28
Original
796 people have browsed it

How to Find the Nearest Number in an Array Using the Reduce Function?

Determine the Nearest Number in an Array

Given an array and a number within the range of -1000 to 1000, the objective is to update the given number to be the closest number present in the array. For instance, if the given number is 80 and the array contains [2, 42, 82, 122, 162, 202, 242, 282, 322, 362], the number should be modified to 82.

To achieve this, we can utilize the ES5 reduce function. The reduce function accumulates the values in the array and returns a single result. In this case, we can use it to find the number in the array that has the smallest absolute difference from the given number.

The reduce function takes a callback as an argument. The callback should return a single value and takes two parameters: the previous value (starting with the first element of the array) and the current value being iterated over.

In the callback, we calculate the absolute difference between the current value and the goal (the given number). We then compare this difference to the absolute difference between the previous value and the goal. If the difference is smaller for the current value, we update the previous value to be the current value.

The reduce function continues iterating through the array, accumulating the closest number to the goal. Once the entire array has been iterated over, the reduce function returns the closest number.

Example:

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

The above is the detailed content of How to Find the Nearest Number in an Array Using the Reduce Function?. 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