Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

108
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda