1

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?

Laurent
  • 539
  • 1
  • 5
  • 11

5 Answers5

11

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]);
}
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
2

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]);
}
Suren Srapyan
  • 66,568
  • 14
  • 114
  • 112
0

Just use %

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

for(let i = 0; i < wanted; i++) {
    console.log(arr[i % arr.length]);
}
steppefox
  • 1,784
  • 2
  • 14
  • 19
0
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;
    }
}
darijan
  • 9,725
  • 25
  • 38
codeGig
  • 1,024
  • 1
  • 8
  • 11
0
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.

Elie Nassif
  • 464
  • 4
  • 11