# Best way to find two numbers in an array whose sum is a specific number with JavaScript?

JavascriptWeb DevelopmentObject Oriented Programming

#### JavaScript for beginners

Best Seller

74 Lectures 10 hours

#### Modern Javascript for Beginners + Javascript Projects

Most Popular

112 Lectures 15 hours

#### The Complete Full-Stack JavaScript Course!

Best Seller

96 Lectures 24 hours

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 }