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

103
Vistas
Resetting index in a for loop

This function needs to find the first occurrence of consecutive numbers whose sum equals 10, and return them as an array. My idea was to keep summing the numbers until the accumulator, in this case x becomes greater than 10, at which point the value of x is reset to zero, and i is reset back to index 1, by being assigned to the ct variable that is supposed to grow by one on each reset, so the loop would go back and start at the next element, until it gets the correct value. But for some reason ct is stuck at 1 and doesn't grow and the loop doesn't move past the second array element at index 1. Is there an error in the logic or the implementation?

Warning: This code may cause the page to crash or become unresponsive

const arr = [2, 3, 1, 2, 7, 2, 5, 4, 5, 1, 2, 1];

function test(arr) {
  let x = 0;
  for (let i = 0; i < arr.length; i++) {
    let ct = 0;
    x = x + arr[i]
    if (x > 10) {
      x = 0;
      i = ct;
      ct++
    }
    console.log(x)
  }
}

console.log(test(arr))

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

The problem is that you've defined ct in the wrong place. It's inside the loop, meaning that every time you get to a point where i = ct, i is reset to 0 and ct++ has no effect (because every iteration, ct is reset to 0). You need to define ct in the same scope as x:

const arr = [2, 3, 1, 2, 7, 2, 5, 4, 5, 1, 2, 1];

function test(arr) {

  let x = 0;
  let ct = 0;

  for (let i = 0; i < arr.length; i++) {
    x = x + arr[i];

    if (x > 10) {
      x = 0;
      i = ct;
      ct++;
    }

    console.log(x);
  }
}

test(arr);

I've also filled in the rest of the logic of the function for you in case you'd like it:

const arr = [2, 3, 1, 2, 7, 2, 5, 4, 5, 1, 2, 1];

function test(arr) {

  let x = 0;
  let ct = 0;
  
  let result = [];

  for (let i = 0; i < arr.length; i++) {
    x = x + arr[i];

    if (x > 10) {
      x = 0;
      i = ct;
      ct++;
    }

    if (x == 10) {
      result = arr.slice(ct, i + 1);
      return result;
    }

    console.log(x);
  }
  return result;
}

console.log(test(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