Home  >  Article  >  Web Front-end  >  How to Find the Nearest Number in an Array Using JavaScript?

How to Find the Nearest Number in an Array Using JavaScript?

Susan Sarandon
Susan SarandonOriginal
2024-10-30 02:50:03922browse

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!

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
Previous article:NGV: pluginsNext article:NGV: plugins