We are required to write a JavaScript function that takes in an array of Numbers. The function should pick a pair of two numbers which are at different indices (consecutive or nonconsecutive) whose sum also exists in the array.
Example
Following is the code −
const arr = [1, 3, 5, 6, 8, 9];
const findPair = (arr = []) => {
let count = 0;
for(let i = 0; i < arr.length; i++){
for(let j = 0; j < arr.length; j++){
if(i === j){
break;
};
let sum = arr[i] + arr[j];
if(arr.includes(sum)){
return [arr[i], arr[j]];
};
};
};
return [];
};
console.log(findPair(arr));Output
Following is the output on console −
[5, 1]