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 }
Updated on: 2020-09-01T11:11:42+05:30

464 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements