DevMoutarde
DevMoutarde

Reputation: 597

Loop through an array of numbers and do something 'number' of times without having two loops?

Currently I have that script :

var array = [1,5];

array.forEach(function(i) {
      something(i);
    });

function something(i){ 
    for(j=1; j <= i; j++) {
        console.log('item displayed ' + j + ' times');     
    }
}

Result is the following :

item displayed 1 times
item displayed 1 times
item displayed 2 times
item displayed 3 times
item displayed 4 times

And I wonder if I can loop through the array, as many times as the current value actually is ? To avoid having two loops.

Upvotes: 2

Views: 192

Answers (1)

Nina Scholz
Nina Scholz

Reputation: 386560

You could add a second counter for the value whcih counts up to the item's value.

var array = [1, 5];

for (let i = 0, j = 1; i < array.length; j < array[i] ? j++ : (j = 1, i++))
    console.log(i, j);

Upvotes: 1

Related Questions