Sometimes, we may want to get the closest number to a given number out of a JavaScript array.
In this article, we’ll look at how to get the closest number to a number out of a JavaScript array.
Using the Array.prototype.reduce Method
One way to get the closest number to a number out of a JavaScript array is to use the JavaScript array’s reduce
method.
To use it, we write:
const arr = [2, 42, 82, 122, 162, 202, 242, 282, 322, 362]
const goal = 100
const closest = arr.reduce((prev, curr) => {
return (Math.abs(curr - goal) < Math.abs(prev - goal) ? curr : prev);
});
console.log(closest)
We have the arr
array that has a bunch of numbers.
goal
is the number that we want to find the closest number in arr
from.
We then pass in the callback into the reduce
method that compares the absolute value of the difference between curr — goal
and prev-goal
.
prev
is the previously closest number to goal
.
And curr
is the current number that’s being iterated through.
If curr
is closer to goal
that prev
in absolute value, then we return curr
.
Otherwise, we return goal
.
Therefore, closest
is 82.
Use the Array.prototype.map Method
Another way to find the closest number to a given number is to map all the array entries to the absolute difference between the number in the array and the goal number.
Then we can use Math.min
to find the minimum difference between the numbers.
For instance, we can write:
const arr = [2, 42, 82, 122, 162, 202, 242, 282, 322, 362]
const goal = 100
const indexArr = arr.map((num) => {
return Math.abs(num - goal)
})
const min = Math.min(...indexArr)
const closest = arr[indexArr.indexOf(min)]
console.log(closest)
We call map
with a callback that returns the absolute difference between num
and goal
.
Then we find the minimum of the differences with Math.min
.
And then we get the index of the number with the lowest absolute difference with indexOf
and pass that into arr
to get the number that’s closest to goal
.
So we get the same result as the previous example.
Conclusion
We can use JavaScript array and math methods to get the number that’s closest to the given number in an array with JavaScript.