Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

144
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda