
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
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