Home > database >  Loop through list of colors while maintaining order
Loop through list of colors while maintaining order

Time:11-18

Let's say I have a list of colors, such as

let ListOfColors = ["Red", "Blue", "Yellow"];

I need to iterate over it via a function that receives a number of elements to print, so that it behaves like this:

If the number of elements to print is 5, it should print

Red
Blue
Yellow
Red
Blue

As you can see, as soon as the current iteration exceeds the total number of colors, it starts again.

For the moment, this is what I have:

function TestColorIteration(NumberOfTimesToIterate)
{
    let ListOfColors = ["Red", "Blue", "Yellow"];

    for(let i = 0; i< NumberOfTimesToIterate; i  )
    {
       console.log(ListOfColors[i])
    }
}

But it does not start the cycle again, it prints undefined.

CodePudding user response:

The modulo operator (%) returns the remainder after integer division.

function TestColorIteration(NumberOfTimesToIterate)
{
    let ListOfColors = ["Red", "Blue", "Yellow"];
    let Count = ListOfColors.length;

    for(let i = 0; i< NumberOfTimesToIterate; i  )
    {
       console.log(ListOfColors[i % Count])
    }
}

You were seeing undefined because the i index was growing to greater than the length of the array. Trying to access an element outside the "bounds" of an array will return undefined.

CodePudding user response:

This is easier to implement with a while loop.

What is happening is you are reaching the last element in the array and then trying to get more elements, but there are no more elements which in turn gives you undefined.

You need to reset your "position" in the array once you have reached the max elements in the array.

function TestColorIteration(NumberOfTimesToIterate)
{
    let ListOfColors = ["Red", "Blue", "Yellow"];
    
    let counter = 0;
    let listElem = 0;
    
    while(counter < NumberOfTimesToIterate)
    {
      console.log(ListOfColors[listElem]);
      
      counter  ;
      listElem  ;
      
      if(counter == ListOfColors.length)
      {
        listElem = 0;
      }
      
    }

}

TestColorIteration(5);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

The simplest solution is by using two loops.

function TestColorIteration(NumberOfTimesToIterate)
{
    let ListOfColors = ["Red", "Blue", "Yellow"];
    var fullRounds = Math.floor(NumberOfTimesToIterate/ListOfColors.length)
    var remainder  = NumberOfTimesToIterate%ListOfColors.length

    for(let i = 0; i< fullRounds; i  )
    {
       console.log(ListOfColors[0])
       console.log(ListOfColors[1])
       console.log(ListOfColors[2])
    }

    for(let i = 0; i< remainder; i  )
    {
       console.log(ListOfColors[i])
    }
}

  • Related