Computer >> Computer tutorials >  >> Programming >> Javascript

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