

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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 Questions & Answers
- 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 the only out of sequence number from an array using JavaScript
- Finding two closest elements to a specific number in an array using JavaScript
- Index of closest element in JavaScript
- Adjacent elements of array whose sum is closest to 0 - JavaScript
- Finding closest pair sum of numbers to a given number in JavaScript
- Finding out the Harshad number JavaScript
- Form a sequence out of an array in JavaScript
- How to get random value out of an array in PHP?
- Get the number of true/false values in an array using JavaScript?
- How to filter out common array in array of arrays in JavaScript
- Filtering out primes from an array - JavaScript
Advertisements