Laurent
Laurent

Reputation: 589

How to start over when there are no more elements in a loop?

Let's say I "want" 6 elements from an array which only contains 3. If the end is reached, start over.

Example:

let arr = ["a", "b", "c"];
let wanted = 5;

for(let i = 0; i < wanted; i++) {
    console.log(arr[i]);
}

Which of course returns:

a
b
c
undefined
undefined

Instead, I need:

a
b
c
a
b

Is there a way to start from the beginning of the array after the elements are over?

Upvotes: 1

Views: 172

Answers (5)

Pranav C Balan
Pranav C Balan

Reputation: 115222

Get the remainder using %(Remainder) operator.

console.log(arr[i % arr.length]);

The remainder value would be within the array index range.

For example: when i reaches to

  • 3 => 3 % 3 = 0
  • 4 => 4 % 3 = 1
  • 0 => 0 % 3 = 0.

let arr = ["a", "b", "c"];
let wanted = 5;

for (let i = 0; i < wanted; i++) {
  console.log(arr[i % arr.length]);
}

Upvotes: 11

codeGig
codeGig

Reputation: 1064

let arr = ["a", "b", "c"];
let wanted = 5;    

for (let i = 0; i < wanted; i++) {
    console.log(arr[i]);
    if (arr.length == i) {
        i = 0;
    }
}

Upvotes: 0

Elie Nassif
Elie Nassif

Reputation: 462

if (i+1 == arr.length){
 console.log(arr[i]);
 i=0;
 wanted =wanted-arr.length;
}else{
 console.log(arr[i]);
}

the loop will work normally until your counter is at the last element, then it will be reset to 0 to start over and will keep doing this until you have reached your wanted number of elements.

Upvotes: 0

steppefox
steppefox

Reputation: 1844

Just use %

let arr = ["a", "b", "c"];
let wanted = 5;

for(let i = 0; i < wanted; i++) {
    console.log(arr[i % arr.length]);
}

Upvotes: 0

Suren Srapyan
Suren Srapyan

Reputation: 68645

You can use (%) remainder operator. It will get index started from 0 till arr.length - 1.

First step is

[0 % 3] === 0 whole 0 remainder, 
[1 % 3] === 0 whole 1 remainder,
[2 % 3] === 0 whole 2 remainder
[3 % 3] === 1 whole 0 remainder
[4 % 3] === 1 whole 1 remainder

let arr = ["a", "b", "c"];
let wanted = 5;

for(let i = 0; i < wanted; i++) {
    console.log(arr[i % arr.length]);
}

Upvotes: 2

Related Questions