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.