
- Javascript Basics Tutorial
- Javascript - Home
- Javascript - Overview
- Javascript - Syntax
- Javascript - Enabling
- Javascript - Placement
- Javascript - Variables
- Javascript - Operators
- Javascript - If...Else
- Javascript - Switch Case
- Javascript - While Loop
- Javascript - For Loop
- Javascript - For...in
- Javascript - Loop Control
- Javascript - Functions
- Javascript - Events
- Javascript - Cookies
- Javascript - Page Redirect
- Javascript - Dialog Boxes
- Javascript - Void Keyword
- Javascript - Page Printing
- JavaScript Objects
- Javascript - Objects
- Javascript - Number
- Javascript - Boolean
- Javascript - Strings
- Javascript - Arrays
- Javascript - Date
- Javascript - Math
- Javascript - RegExp
- Javascript - HTML DOM
- JavaScript Advanced
- Javascript - Error Handling
- Javascript - Validations
- Javascript - Animation
- Javascript - Multimedia
- Javascript - Debugging
- Javascript - Image Map
- Javascript - Browsers
- JavaScript Useful Resources
- Javascript - Questions And Answers
- Javascript - Quick Guide
- Javascript - Functions
- Javascript - Resources
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
- Related Articles
- Find Sum of pair from two arrays with maximum sum in C++
- Finding three elements with required sum in an array in JavaScript
- Find a pair with given sum in BST in C++
- Achieving maximum possible pair sum in JavaScript
- Find the Pair with Given Sum in a Matrix using C++
- Find a pair with given sum in a Balanced BST in C++
- Find a pair with given sum in a Balanced BST in Java
- Find the Pair with a Maximum Sum in a Matrix using C++
- JavaScript Program to Find a pair with the given difference
- Pair whose sum exists in the array in JavaScript
- Find pairs with given sum such that pair elements lie in different BSTs in Python
- JavaScript Program to Find all triplets with zero sum
- Python Program to Filter Rows with a specific Pair Sum
- C++ Largest Subset with Sum of Every Pair as Prime
- Find pairs with given sum such that elements of pair are in different rows in Python

Advertisements