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

JavascriptWeb DevelopmentFront End Technology

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];

Example

Following is the code −

 Live Demo

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));

Output

[2, 3]
raja
Published on 24-Apr-2021 14:02:37
Advertisements