-2

Java script, I have a list, animals = [cat, dog, another_cat, another_dog, mouse, squirrel, etc.]

and another list, numbers = [2, 3, 4]

I am looping the animals list. for( i = 0; i < animals.length; i++) console.log = (numbers)

I need "console.log = (numbers)" on the first loop to give me 2, on the next one to give me 3, next 4, next 2...3...4

I apologize again if I wasn't clear.

Adrian
  • 3
  • 3

1 Answers1

0

Try using the remainder operator (%) and the length of the array to calculate.

const animals = ['cat', 'dog', 'another_cat', 'another_dog', 'mouse', 'squirrel'];

const numbers = [2, 3, 4];

for (let i = 0, counter = 0 ; counter < animals.length; ++counter) {
    console.log(`number: ${numbers[i]}, animal: ${animals[counter]}`);
    i = (i + 1) % numbers.length;
}
Ian
  • 1,198
  • 1
  • 5
  • 15
  • Hi, thank you for the elaborate answer, but I guess my question wasn't clear, let me rephrase it. I have a list, animals = [cat, dog, another_cat, another_dog, mouse, squirrel, etc.] and another list, numbers = [2, 3, 4] I am looping the animals list. for( i = 0; i < animals .length; i++) {console.log = (numbers) } I need "console.log = (numbers)" on the first loop to give me 2, on the next one to give me 3, next 4, next 2...3...4 I apologize again if I wasn't clear. – Adrian Aug 12 '22 at 04:37
  • Hi @Adrian I re-edited my answer, you can refer to it again – Ian Aug 12 '22 at 06:08