Aiman_Irfan
Aiman_Irfan

Reputation: 375

How to make a loop that go up and down at the same time?

i was wandering how to make a loop that go up and down at the same time.

For example, here is the normal loop:

for(let i = 0; i < number.length; i++){}

for(let i = 0; i < number.length; i--){}

How can i simplify this loop?

Upvotes: 1

Views: 637

Answers (3)

georg
georg

Reputation: 215029

You can have as many indexes as you want in a for loop:

a = [1,2,3,4,5,6,7]

for (let i = 0, k = a.length - 1; i < a.length && k >= 0; i++, k--) {
    console.log(i, k)
}

or, you can compute the second index from the first

a = [1,2,3,4,5,6,7]

for (let i = 0; i < a.length; i++) {
    let k = a.length - 1 - i
    console.log(i, k)
}

If you want to do that in the modern way, without any indexes at all, this would require some runtime support:

function* iter(a) {
    yield* a;
}

function* reversed(a) {
    yield* [...a].reverse();
}

function* zip(...args) {
    let iters = args.map(iter);
    while (1) {
        let rs = iters.map(it => it.next());
        if (rs.some(r => r.done))
            break;
        yield rs.map(r => r.value);
    }
}

//

a = 'abcdef'

// just like in python!
for (let [x, y] of zip(a, reversed(a)))
    console.log(x, y)

Upvotes: 6

Muhammad Hassan Nasir
Muhammad Hassan Nasir

Reputation: 38

If you want to get the values from first to the last value and vise versa at the same time you don't have to use double loops. Instead just use the i and arrays length. Here's an example.

var length = number.length - 1
for(let i = 0; i < number.length; i++){
   console.log(number[i])
   console.log(number[length-i])
}

Upvotes: 0

Reedy
Reedy

Reputation: 77

You could just embed 2 loops. Such as:

for(let i = 0; i < number.length; i++){  // i going "up"
  for(let j = number.length; j > 0; j--){}  // j going "down"
}

Upvotes: 1

Related Questions