0

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));

2
  • can you give some examples of valid inputs and outputs to make that posting clear? Commented Jul 20, 2022 at 20:41
  • 1
    The break aborts the inner j-loop every time after j===0 has been attempted. Commented Jul 20, 2022 at 20:44

1 Answer 1

1

Your implementation doesn't work for all positive numbers either. Try 3 as sum.

I believe you want to put the break statement inside the if statement or just replace the body of the if statement with return [arr[j], arr[i]]:

const sumOfPairs = (arr, sum) => {
  for (let i = 0; i < arr.length; i++) {
    for (let j = 0; j < arr.length; j++) {
      if (arr[i] + arr[j] === sum && i != j) {
        // You can return here if you only want to find *one* pair
        // You also need add some additional logic if you want them
        // to be in the same order as in the original array:
        return i < j ? [arr[i], arr[j]] : [arr[j], arr[i]]
      }
    }
  }
  return []
}

console.log(sumOfPairs([1, -2, 3, 0, -6, 1], -6));

The current location of the break statement in your loop causes the inner loop to terminate after its first iteration! Therefore the inner loop is equivalent to testing whether the sum of the current outer loop's item (arr[i]) and 1 (the first element in the array) is equal the provided sum.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.