Finding two closest elements to a specific number in an array using JavaScript

Finding the two closest elements to a specific number in an array is a common algorithmic problem. This article demonstrates how to solve it efficiently using JavaScript's array methods and mathematical calculations.

Problem

We are required to write a JavaScript function that takes in an array of sorted integers, arr, as the first argument and a target number, as the second argument.

Our function should return an array of exactly two numbers that exists in the array arr and are closest to target. The output array should also be sorted in increasing order.

For example, if the input to the function is:

Input

const arr = [1, 2, 3, 4, 5];
const target = 3;

Output

const output = [2, 3];

Using Sort and Distance Calculation

The approach sorts elements by their distance from the target, then takes the first two elements and sorts them in ascending order:

const arr = [1, 2, 3, 4, 5];
const target = 3;

const findClosest = (arr = [], target = 1) => {
    const size = 2;
    return arr.sort((a, b) => {
        const distanceA = Math.abs(a - target);
        const distanceB = Math.abs(b - target);
        if (distanceA === distanceB) {
            return a - b;
        }
        return distanceA - distanceB;
    }).slice(0, size)
    .sort((a, b) => a - b);
};

console.log(findClosest(arr, target));
[2, 3]

How It Works

The algorithm works in three steps:

  1. Distance Calculation: Calculate absolute difference between each element and target using Math.abs()
  2. Sort by Distance: Sort array by distance from target (closest first)
  3. Extract and Sort: Take first two elements and sort them in ascending order

Testing with Different Targets

const arr = [1, 2, 3, 4, 5, 8, 10];

// Test different targets
console.log("Target 6:", findClosest(arr, 6));   // Closest to 6
console.log("Target 1:", findClosest(arr, 1));   // Closest to 1
console.log("Target 9:", findClosest(arr, 9));   // Closest to 9

function findClosest(arr = [], target = 1) {
    const size = 2;
    return arr.sort((a, b) => {
        const distanceA = Math.abs(a - target);
        const distanceB = Math.abs(b - target);
        if (distanceA === distanceB) {
            return a - b;
        }
        return distanceA - distanceB;
    }).slice(0, size)
    .sort((a, b) => a - b);
}
Target 6: [5, 8]
Target 1: [1, 2]
Target 9: [8, 10]

Key Points

  • The algorithm modifies the original array during sorting
  • When distances are equal, smaller numbers are prioritized
  • Final result is always sorted in ascending order
  • Time complexity: O(n log n) due to sorting operations

Conclusion

This solution efficiently finds the two closest elements by sorting elements based on their distance from the target. The approach ensures the result is always in ascending order and handles edge cases where multiple elements have equal distances.

Updated on: 2026-03-15T23:19:00+05:30

877 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements