Find required sum pair with JavaScript


Let’s say, we are required to write a function that takes in an array and a number and returns the index of the first element of the first pair from the array that adds up to the provided number, if there exists no such pair in the array, we have to return -1.

By pair, we mean, two consecutive elements of the array and not any two arbitrary elements of the array. So, let’s write the code for this function −

Example

const arr = [4, 8, 2, 7, 6, 42, 41, 77, 32, 9];
const findPair = (arr, num) => {
   for(let i = 0; i < arr.length; i++){
      if(arr[i] + arr[i+1] === num){
         return i;
      }
   };
   return -1;
};
console.log(findPair(arr, 13));
console.log(findPair(arr, 48));
console.log(findPair(arr, 45));

Output

The output in the console will be −

3
4
-1

Updated on: 20-Aug-2020

364 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements