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

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

Susan Sarandon
Release: 2024-10-30 02:50:03
Original
922 people have browsed it

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

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!

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!