Finding closest pair sum of numbers to a given number in JavaScript


We are required to write a JavaScript function that takes in an array of Numbers as the first argument and a Number as the second argument.

The function should return an array of two numbers from the original array whose sum is closest to the number provided as the second argument.

The code for this will be −

const arr = [1, 2, 3, 4, 5, 6, 7];
const num = 14;
const closestPair = (arr, sum) => {
   let first = 0, second = 0;
   for(let i in arr) {
      for(let j in arr) {
         if(i != j) {
            let tmp = arr[i] + arr[j];
            if(tmp <= sum && tmp > first + second) {
               first = arr[i];
               second = arr[j];
            }
         };
      };
   };
   return [first, second];
};
console.log(closestPair(arr, num));

Following is the output on console −

[6, 7]

Updated on: 09-Oct-2020

187 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements