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

102
Views
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 answers
Answer question

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 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!