Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

146
Views
Adding Negative Integers in Javascript

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

about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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.

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!