Sling Academy
Home/JavaScript/JavaScript: 2 Ways to Find the Nearest Value in an Array

JavaScript: 2 Ways to Find the Nearest Value in an Array

Last updated: January 22, 2024

Introduction

When you work with arrays in JavaScript, a common task is to locate the element nearest to a given value. Whether for numeric arrays or more complex data structures, JavaScript provides different approaches to achieve this. Various solutions offer a trade-off between ease of implementation and performance. This tutorial introduces the different ways to find the nearest value in an array using JavaScript.

Performing a linear search is a straightforward approach to find the nearest value by iterating through each element in the array and comparing it to the target value.

  1. Initialize the nearest value and the smallest difference.
  2. Loop through each element in the array.
  3. Calculate the absolute difference between the target value and each element.
  4. If the calculated difference is smaller than the smallest difference, update the nearest value and the smallest difference.
  5. Repeat the process until the end of the array.
  6. Return the nearest value.

Example:

const findNearest = (arr, target) => {
  let nearest = arr[0];
  let smallestDifference = Math.abs(target - nearest);
  for (let i = 1; i < arr.length; i++) {
    const difference = Math.abs(target - arr[i]);
    if (difference < smallestDifference) {
      nearest = arr[i];
      smallestDifference = difference;
    }
  }
  return nearest;
};

console.log(findNearest([5, 20, 12, 16, 22], 15)); // Output: 16

Notes: The linear search solution has a O(n) complexity where n is the size of the array. This approach is simple but not optimized for large datasets. Performing well on smaller arrays but may become inefficient for large arrays.

By sorting the array first, you can apply a binary search technique to find the element nearest to a given value, significantly reducing the search time.

  1. Sort the array in ascending order.
  2. Implement a binary search to locate the nearest value.
  3. If the exact match is found, return it.
  4. Use two pointers to find the closest values when there’s no exact match.
  5. Return the nearest value based on which pointer indicates the smaller difference to the target.

Example:

const findNearestUsingBinarySearch = (arr, target) => {
  arr.sort((a, b) => a - b);
  let start = 0;
  let end = arr.length - 1;
  while (start <= end) {
    let mid = Math.floor((start + end) / 2);
    if (arr[mid] === target) return arr[mid];
    if (arr[mid] < target) start = mid + 1;
    else end = mid - 1;
  }
  const closest = (target - arr[end] <= arr[start] - target) ? arr[end] : arr[start];
  return closest;
};

console.log(findNearestUsingBinarySearch([5, 20, 12, 16, 22], 15)); // Output: 16

Notes: Sorting the array first introduces an additional O(n log n) complexity. The binary search itself has a O(log n) complexity, thus it is more efficient on sorted datasets. Sorting might not be feasible if the order in the original array must be preserved or if sorting introduces a significant overhead.

Conclusion

Identifying the nearest value in an array can be achieved through various methods in JavaScript, each with its own characteristics. Linear search is easy to understand and implement but does not perform well with large datasets. On the other hand, sorting the array before employing a binary search optimizes the search operation, particularly compelling for large, sortable arrays. Developers should choose the approach that best fits their circumstance, considering factors such as array size, need to maintain the original order, and performance implications.

Next Article: JavaScript: How to Identify Mode(s) of an Array (3 Approaches)

Previous Article: JavaScript Array.toSpliced() method (with examples)

Series: Working with Arrays in JavaScript

JavaScript

You May Also Like

  • Handle Zoom and Scroll with the Visual Viewport API in JavaScript
  • Improve Security Posture Using JavaScript Trusted Types
  • Allow Seamless Device Switching Using JavaScript Remote Playback
  • Update Content Proactively with the JavaScript Push API
  • Simplify Tooltip and Dropdown Creation via JavaScript Popover API
  • Improve User Experience Through Performance Metrics in JavaScript
  • Coordinate Workers Using Channel Messaging in JavaScript
  • Exchange Data Between Iframes Using Channel Messaging in JavaScript
  • Manipulating Time Zones in JavaScript Without Libraries
  • Solving Simple Algebraic Equations Using JavaScript Math Functions
  • Emulating Traditional OOP Constructs with JavaScript Classes
  • Smoothing Out User Flows: Focus Management Techniques in JavaScript
  • Creating Dynamic Timers and Counters with JavaScript
  • Implement Old-School Data Fetching Using JavaScript XMLHttpRequest
  • Load Dynamic Content Without Reloading via XMLHttpRequest in JavaScript
  • Manage Error Handling and Timeouts Using XMLHttpRequest in JavaScript
  • Handle XML and JSON Responses via JavaScript XMLHttpRequest
  • Make AJAX Requests with XMLHttpRequest in JavaScript
  • Customize Subtitle Styling Using JavaScript WebVTT Integration