Categories
JavaScript Answers

How to get the closest number out of an array with JavaScript?

Spread the love

To get the closest number out of an array with JavaScript, we use the reduce method.

For instance, we write

const counts = [4, 9, 15, 6, 2];
const goal = 5;

const closest = counts.reduce((prev, curr) => {
  return Math.abs(curr - goal) < Math.abs(prev - goal) ? curr : prev;
});

console.log(closest);

to call counts.reduce with a callback that checks if curr - goal is smaller than prev - goal in absolute value.

If it is, we return curr.

Otherwise, prev is `returned.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *