- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Get closest number out of array JavaScript
Let’s say, we are required to write a function that takes in an array of numbers and a number as input and returns the closest value that exists in the array to that number.
For example −
closest([45,61,53,98,54,12,69,21], 67); //69 closest([45,61,53,98,54,12,69,21], 64); //61
So, let’s write the code for it.
We will use the Array.prototype.reduce() method to calculate the differences and return the smallest difference from the reduce function and the sum of that smallest difference and the number we were searching for will be our required number.
Here is the code for this −
Example
const closest = (arr, num) => { return arr.reduce((acc, val) => { if(Math.abs(val - num) < Math.abs(acc)){ return val - num; }else{ return acc; } }, Infinity) + num; } console.log(closest([45,61,53,98,54,12,69,21], 67)); console.log(closest([45,61,53,98,54,12,69,21], 64));
Output
The output of this code in the console will be −
69 61
- Related Articles
- Get the closest number out of an array in JavaScript
- Find closest index of array in JavaScript
- Find closest number in array in C++
- Find the closest value of an array in JavaScript
- Finding two closest elements to a specific number in an array using JavaScript
- Adjacent elements of array whose sum is closest to 0 - JavaScript
- Finding the only out of sequence number from an array using JavaScript
- Finding closest pair sum of numbers to a given number in JavaScript
- Index of closest element in JavaScript
- Get the number of true/false values in an array using JavaScript?
- Form a sequence out of an array in JavaScript
- Finding out the Harshad number JavaScript
- How to filter out common array in array of arrays in JavaScript
- How to get random value out of an array in PHP?
- Filtering out primes from an array - JavaScript

Advertisements