Find the closest value of an array in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

We are required to write a JavaScript function that takes in an array of numbers as the first argument and a number as the second argument. The function should then return the number from the array which closest to the number given to the function as second argument.

Example

The code for this will be −

const arr = [3, 56, 56, 23, 7, 76, -2, 345, 45, 76, 3];
const num = 37
const findClosest = (arr, num) => {
   const creds = arr.reduce((acc, val, ind) => {
      let { diff, index } = acc;
      const difference = Math.abs(val - num);
      if(difference < diff){
         diff = difference;
         index = ind;
      };
      return { diff, index };
   }, {
      diff: Infinity,
      index: -1
   });
   return arr[creds.index];
};
console.log(findClosest(arr, num));

Output

The output in the console −

45
raja
Published on 12-Oct-2020 15:19:51
Advertisements