I am trying to write a function that returns the first two values in order of appearance that add to the sum. My function works fine with positive numbers, but not with negative. Can anyone tell me what I am doing wrong?
This function return an empty array:
const sumOfPairs = (arr, sum) => {
const answer = [];
for (let i = 0; i < arr.length; i++) {
for (let j = 0; j < arr.length; j++) {
if (arr[i] + arr[j] === sum && i != j) {
answer.push(arr[j], arr[i]);
}
break;
}
}
return answer;
}
console.log(sumOfPairs([1, -2, 3, 0, -6, 1], -6));
Comments
Post a Comment