Find Closest Number in Array using JavaScript



To find closest number in array using Javascript, we will be understanding and discussing three different approaches. We will also compare time and space complkexities of all the appproaches used.

In this article we are having an array and a target value, our task is to find closest number to target value in array using Javascript. User must know about JavaScript arrays, searching alogorithms such as linear and binary search, sorting, loops, and conditional statement.

Approaches to Find Closest Number in Array

Here is a list of approaches to find closest number in array in JavaScript which we will be discussing in this article with stepwise explanation and complete example codes.

To find closest number in array using Javascript, we have used linear search method where we traverse each element in array and compare the closest value.

  • First we have declared an array as arr and defined a function closestEle() that accepts arr, and target as its arguments.
  • We create a variable closest and set it equal to the first number in the numbers array, and assume that this is the closest number to the target.
  • We have then used a for...of loop to iterate through the numbers array. For each element of array we have calculated the absolute difference between ele and the target using Math.abs() function and stored in currDiff variable.
  • The value of absolute difference of current closest and target is stored in closestDiff variable.
  • Then we have used if/else statement to determine closest element. We have compared currDiff with closestDiff, if currDiff is less than closestDiff then currDiff is stored in closest.
  • Finally, the function returns the closest number to the target and is displayed in web console using console.log().

Example

Here is a complete example code implementing above mentioned steps to find closest number in array in JavaScript using linear search.

let arr = [4, 20, 46, 87], target = 63;
function closestEle(arr, target) {
    let closest= arr[0];
    for (let ele of arr) {
        let currDiff = Math.abs(ele - target); 
        let closestDiff = Math.abs(closest - target);
        if (currDiff 

In this approach to find closest number in array using Javascript, we have used binary search.

  • First we have declared an array as arr and defined a function closestEle() that accepts arr, and target as its arguments. Inside function we have defined two more variables as l and r representing leftmost and rightmost element of the array.
  • Then we have calculated the mid element of the array and used Math.floor() function to round down the number.
  • Then, we have used if/else statement to compare the target where we first compare the target with mid element od the array. If the target is found we return the array value at the index specified by mid.
  • If the target is not the middle element, then we check if mid element is less than target and set the left pointer as mid + 1; and mid value is assigned to right pointer otherwise. This process keeps repeating untill left pointer is less than right pointer using while loop.
  • Then we have calculated the abosulte differences of target and previous value of left pointer, and target and left pointer. These differences are stored in prevDiff and currDiff. These values are then compared using if/else statement.
  • If prevDiff is smaller than currDiff, then value of prevDiff i.e arr[l-1] is returned.

Example

Here is a complete example code implementing above mentioned steps to find closest number in array in JavaScript using binary search.

let arr = [4, 20, 46, 87], target = 63;
function closestEle(arr, target) {
    let l = 0, r = arr.length - 1;
    while (l  0) {
        const prevDiff = Math.abs(arr[l - 1] - target);
        const currDiff = Math.abs(arr[l] - target);
        if (prevDiff 

Using Two Pointer

In this approach, we have used two pointer technique to find closest number in array using Javascript.

  • First we have declared an array as arr and defined a function closestEle() that accepts arr, and target as its arguments. Inside the function we have defined two pointers storing leftmost and rightmost index of array and one variable is defined storing first element of array as closest element.
  • Then we have used while loop that iterates untill left pointer is less than right pointer. We have defined three more variables inside while loop which stores the absolute differences.
  • Then we have used two if conditions that compares leftDiff and rightDiff with closestDiff. The conditional statement is again used for the movement of pointers. If the value of array specified by left index is smaller than target, then left pointer is incremented by 1, similarly right pointer is decreased by 1 if value of array specified by right index is greater than target.
  • Then we have returned the closest variable and result is displayed in web console using console.log().

Example

Here is a complete example code implementing above mentioned steps to find closest number in array in JavaScript using two pointer method.

let arr = [4, 20, 46, 87], target = 63;
function closestEle(arr, target) {
    let left = 0, right = arr.length - 1;
    let closest = arr[0];
    while (left  target) {
            right--;
        } else {
            return arr[left];
        }
    }
    return closest;
}
console.log("Closest number to " +target +" is: " 
            +closestEle(arr, target));

Complexity Comparison

Here is a comparison of time and space complexity of all the above approaches.

Approach Time Complexity Space Complexity
Linear Search O(n) O(1)
Binary Search O(log n) O(1)
Two Pointer O(n) O(1)

Conclusion

In this article, to find closest number in array using Javascript we have understood three different approaches which are: using linear search, binary search and two pointer approach. Among all three appraoches binary search has minimum time complexity.

Practice and learn from a wide range of JavaScript examples, including event handling, form validation, and advanced techniques. Interactive code snippets for hands-on learning.
Updated on: 2024-12-05T15:09:54+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements