Find the nearest element in an array in JavaScript with one line

One array is given and a number is given. Find the nearest value of that number in the array in one line. Try not to use a for loop.

const findNearest = (arr, num) =>
    (acc, value) => (Math.abs(acc - num) < Math.abs(value - num) ? acc : value),

const givenArray = [1, 4, 6, 8, 9, 15, 21];

console.log(findNearest(givenArray, 2));
console.log(findNearest(givenArray, 11));
console.log(findNearest(givenArray, 14));
console.log(findNearest(givenArray, 16));
console.log(findNearest(givenArray, 20));


  • findNearest takes an array and returns the nearest value to num in that array.

  • We are using reduce. It takes one function as the first param and calculate one single value from the values of the array

  • acc is the accumulator i.e. it computes and holds the final value and value is the current value in the array.

  • We are using Math.abs to find the absolute value.

  • On each step, it tries to find the closest element to num by comparing the difference between accumulator and current value with current value and given number.

It prints :