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:
xxxxxxxxxx
1
const goal = 4;
2
const numbers = [1, 2, 8, 9];
3
4
const closest = numbers.reduce((prev, curr) => {
5
return Math.abs(curr - goal) < Math.abs(prev - goal) ? curr : prev;
6
});
7
8
console.log(closest); // 2
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.
xxxxxxxxxx
1
const findClosest = (array, goal) => {
2
return array.reduce((prev, curr) => {
3
return Math.abs(curr - goal) < Math.abs(prev - goal) ? curr : prev;
4
});
5
};
6
7
8
// Usage example:
9
10
const goal = 4;
11
const numbers = [1, 2, 8, 9];
12
13
const closestValue = findClosest(numbers, goal);
14
15
console.log('value: ' + closestValue); // 2
xxxxxxxxxx
1
const findClosest = (array, goal) => {
2
if (array.length > 0) {
3
let index = 0;
4
let error = Math.abs(array[0] - goal);
5
for (let i = 1; i < array.length; ++i) {
6
const e = Math.abs(array[i] - goal);
7
if (e < error) {
8
index = i;
9
error = e;
10
}
11
}
12
return index;
13
}
14
return -1;
15
};
16
17
18
// Usage example:
19
20
const goal = 4;
21
const numbers = [1, 2, 8, 9];
22
23
const closestIndex = findClosest(numbers, goal);
24
25
if (closestIndex !== -1) {
26
const closestValue = numbers[closestIndex];
27
28
console.log('index: ' + closestIndex); // 2
29
console.log('value: ' + closestValue); // 8
30
}