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

117
Vistas
Check multiple arrays for zero sum subquence

I would like to check multiple arrays if their sum is equal to zero and if yes, output yes. But only the first array is being read by the code.

There should be 3 outputs of (true or false) but I'm getting only 1 output instead

const arr0 = [3];
const arr1 = [4];
const arr2 = [2, 8, -9, 1];    

const arr = [arr0, arr1, arr2];

const zeroSum = arr => {
   const map = new Map();
   let sum = 0;
   for(let i = 0; i < arr.length; i++){
      sum += arr[i];
      if(sum === 0 || map.get(sum)){
         return true;
      };
      map.set(sum, i);
   };
   return false;
};
console.log(zeroSum(arr));
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

  1. As I mentioned in my comment arr[i] will always be an array. Trying to add that to sum will result in a string. You'll never get the result you want. To sum the elements of each array you need an inner loop to go over each element and add those to sum instead.

  2. Currently you're only returning one thing: true or false. It sounds like you want an array into which you add the results of each sum, and then you can return that.

  3. Not sure what you're using Map for so I've removed it from my example.

const arr0 = [3];
const arr1 = [4];
const arr2 = [0];
const arr3 = [2, 8, -9, 1];    

const arr = [arr0, arr1, arr2, arr3];

function zeroSum(arr) {

  // Create an output array
  const out = [];

  // Loop over the arrays
  for (let i = 0; i < arr.length; i++) {

    // Reset the sum for each iteration
    let sum = 0;
    const inner = arr[i];

    // Loop over the elements of each array
    for (let j = 0; j < inner.length; j++) {

     // Add the elements to `sum`
     sum += inner[j];
    }

    // Push either true or false to
    // the output array depending on the
    // result of the condition
    if (sum === 0) {
      out.push(true);
    } else {
      out.push(false);
    }
  }

  // Finally return the array
  return out;
}

console.log(zeroSum(arr));

about 4 years ago · Juan Pablo Isaza 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