EN
JavaScript - find closest number to given value in array
3
points
In this article, we would like to show you how to find the closest number in an array to the given value in JavaScript.
Quick solution:
// ONLINE-RUNNER:browser;
const goal = 4;
const numbers = [1, 2, 8, 9];
const closest = numbers.reduce((prev, curr) => {
return Math.abs(curr - goal) < Math.abs(prev - goal) ? curr : prev;
});
console.log(closest); // 2
Reusable code examples
1. Array
reduce()
method based example
In this example, we use Array
reduce()
method with Math.abs()
to find the closest number to the goal
in numbers
array by comparing absolute values of the differences.
// ONLINE-RUNNER:browser;
const findClosest = (array, goal) => {
return array.reduce((prev, curr) => {
return Math.abs(curr - goal) < Math.abs(prev - goal) ? curr : prev;
});
};
// Usage example:
const goal = 4;
const numbers = [1, 2, 8, 9];
const closestValue = findClosest(numbers, goal);
console.log('value: ' + closestValue); // 2
2. for
loop based example
// ONLINE-RUNNER:browser;
const findClosest = (array, goal) => {
if (array.length > 0) {
let index = 0;
let error = Math.abs(array[0] - goal);
for (let i = 1; i < array.length; ++i) {
const e = Math.abs(array[i] - goal);
if (e < error) {
index = i;
error = e;
}
}
return index;
}
return -1;
};
// Usage example:
const goal = 4;
const numbers = [1, 2, 8, 9];
const closestIndex = findClosest(numbers, goal);
if (closestIndex !== -1) {
const closestValue = numbers[closestIndex];
console.log('index: ' + closestIndex); // 2
console.log('value: ' + closestValue); // 8
}