Languages
[Edit]
EN

JavaScript - find closest number to given value in array

3 points
Created by:
Lily
548

In this article, we would like to show you how to find the closest number in an array to the given value in JavaScript.

Quick solution:

 

Reusable code examples

Edit

1. Array reduce() method based example

Edit

In this example, we use Array reduce() method with Math.abs() to find the closest number to the goal in numbers array by comparing absolute values of the differences.

2. for loop based example

Edit

 

See also

Edit
  1. JavaScript - Math.abs() method example

References

Edit
  1. Math.abs() - JavaScript | MDN
  2. Array.prototype.reduce() - JavaScript | MDN

Alternative titles

  1. JavaScript - find nearest number to value
1
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join