2

Hi I an new to programming and am experiencing looping problems. I have two arrays :

colour = ['red','blue','green','orange'];
rows = [1,2,3,4,5,6,7,8,9,10,11...];

I want to have each row element pair with a colour from the colour array, for example starting

rows[0]=>colours[0],
rows[1]=>colours[1],
rows[2]=>colours[2],
rows[3]=>colours[3],
rows[4]=>colours[0],
rows[5]=>colours[1],.....

I basically want to start iterating over the colours once they runout

1
  • rows.forEach(function (v, i) { rows[i] = colour[i%4]; }); Commented Jan 28, 2013 at 21:59

2 Answers 2

4

Probably something along the lines of this:

var i,
    rowCount,
    colour,
    rows;
colour = ['red', 'blue', 'green', 'orange'];
rows = [];
rowCount = 20;
for (i = 0; i < rowCount; i++) {
    rows[i] = colour[i % colour.length];
}

The key to this working is the modulus operator (remainder after division). i % color.length is the remainder of i divided by color.length, which relates to the indices of colour.

Sign up to request clarification or add additional context in comments.

4 Comments

I had that exact same answer but saw yours as I was about to submit mine... kudos for the speedy answer.
You could probably use i < rows.length instead of rowCount.
@ArthurMigdal, I considered that, but as rows was being overwritten, it seemed more likely that the length was coming in as an external input.
Thanks a million, it worked like a charm. Everyday is a school day :)
0

You could iterate thorugh all rows and assign colors in order. When the collor array is done just reset its index.

    var colorIndex = 0;
    for (var i=0; i<rows.length; ++i)
     {
         row[i] = colours[j]; //use the color for the current row
         j++;
         if (j == colours.length) //when you reached the last colour 
          {
              j = 0; //reset colour index.
          }
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.