You do not need to generate a new array for each div, so while both of your proposed solutions could work, the second one is the better way to go.
When setting the initial color for each div, you simply need to select the color based off the index of the current div.
div[index].style.backgroundColor = colors[index];
Since you can have more divs than colors you need to start from the beginning of the array once the index of the div exceeds the number of colors. As CertainPerformance's answer shows, you can use the modulus of the index to easily "loop" the index back to the beginning. So the assignment becomes:
divs[index].style.backgroundColor = colors[index % colors.length];
Once you've done the initial color assignment one way to iterate through the colors is to simply find the index of the current color and increment one, again using the modulus in order to loop through the colors.
var currentColor = doc.style.backgroundColor;
var colorIndex = (colors.indexOf(currentColor) + 1) % colors.length;
doc.style.backgroundColor = colors[colorIndex];
Here is a complete example.
var colors = ['red', 'blue', 'yellow', 'green', 'purple'];
function assignInitialColors() {
var divs = document.getElementsByClassName("color-change");
for (var index in divs) {
var colorIndex = index % colors.length;
if(divs[index].style) {
divs[index].style.backgroundColor = colors[colorIndex];
}
}
setInterval(iterateColors, 2000);
}
function iterateColors() {
var divs = document.getElementsByClassName("color-change");
for (var index in divs) {
var doc = divs[index];
var currentColor = doc.style && doc.style.backgroundColor;
if (currentColor) {
var colorIndex = (colors.indexOf(currentColor) + 1) % colors.length;
doc.style.backgroundColor = colors[colorIndex];
}
}
}
assignInitialColors();
div, .color-change {
min-height: 60px;
min-width: 60px;
margin: 5px;
float: left;
}
<div class="color-change"></div>
<div class="color-change"></div>
<div class="color-change"></div>
<div class="color-change"></div>
<div class="color-change"></div>
<div class="color-change"></div>
<div class="color-change"></div>
<div class="color-change"></div>
<div class="color-change"></div>
<div class="color-change"></div>
<div class="color-change"></div>
<div class="color-change"></div>
<div class="color-change"></div>
<div class="color-change"></div>