- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Best way to find two numbers in an array whose sum is a specific number with JavaScript?
Let’s say the following is our array −
var numbers = [10,3,40,50,20,30,100]
We need to search two numbers from the above array elements, whose sum is 80.
For this, use simple for loop with if condition.
Example
function specificPairsOfSumOfTwoNumbers(numbers, totalValue) { var storeTwoNumbersObject = {} for(var currentNumber of numbers) { if(storeTwoNumbersObject[currentNumber]) { return { firstNumber: totalValue-currentNumber, secondNumber:currentNumber} } storeTwoNumbersObject[totalValue-currentNumber] = true; } return false; } var numbers = [10,3,40,50,20,30,100] console.log("The Two numbers which has the sum 80="); console.log(specificPairsOfSumOfTwoNumbers(numbers, 80) )
To run the above program, you need to use the following command −
node fileName.js.
Here my file name is demo207.js.
Output
This will produce the following output −
PS C:\Users\Amit\javascript-code> node demo207.js The Two numbers which has the sum 80= { firstNumber: 50, secondNumber: 30 }
Advertisements