Languages
[Edit]
EN

JavaScript - find closest number to given value in array

3 points
Created by:
Lily
548

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
}

 

See also

  1. JavaScript - Math.abs() method example

References

  1. Math.abs() - JavaScript | MDN
  2. Array.prototype.reduce() - JavaScript | MDN

Alternative titles

  1. JavaScript - find nearest number to value
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join