 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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]
Advertisements
 