1

How would I get a standard for loop to output in pairs or other groups (like three's of four's) with the output shifting up one after the last digit of the group?

for(var i = 0: i < 8; i++){
  console.log(i)
}

so instead of the output being; 0,1,2,3,4,5,6,7

In pairs it would be; 0,1,1,2,2,3,3,4

or if it went up in groups of four; 0,1,2,3,1,2,3,4

I did try doing something like this, but instead of going up in two's every time I need the loop to output the first 2 digits move up one then output the next two ect...

 for(var i = 0: i < 8; i+= 2){
      console.log(i)
    }

Hope that makes sense

1
  • Is there a problem with nesting a second loop? Commented Mar 15, 2021 at 13:01

3 Answers 3

1

For each case you would need to come up with the right formula based on i:

so instead of the output being; 0,1,2,3,4,5,6,7 In pairs it would be; 0,1,1,2,2,3,3,4

for (let i = 1; i < 9; i++) {
    console.log(i >> 1); // this bit shift is integer division by 2
}

or if it went up in groups of four; 0,1,2,3,1,2,3,4

for (let i = 0; i < 8; i++) {
    // Perform division by 4 and add remainder to that integer quotient
    console.log((i >> 2) + (i % 4)); 
}

Sign up to request clarification or add additional context in comments.

Comments

0

You could work with a variable inside the loop to determine the index. This way you can specify how many times you want the loop to run:

for(let index = 0; index < 8; index++) {
    const currentIndex = index - (index >> 1);
    console.log(currentIndex);
}

It also makes it easy to implement it as immutable:

const array = new Array(8).fill(0).map((entry, index) => index - (index >> 1));
console.log(array);

Comments

0

I think a function like below where we specify the total n and the chunksize after which you want to increase a single step might work for us :-

function getByChunkSteps(n,chunkSize){
let step = -1;
let output = [];
for(let index = 0;index < n;index++){
  if(index%chunkSize===0){
  step+=1;
  }
    output.push((index%chunkSize)+step);
}
return output;
}

console.log(getByChunkSteps(10,2));
console.log(getByChunkSteps(8,4));
console.log(getByChunkSteps(9,3));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.