JamiePegg
JamiePegg

Reputation: 77

Javascript Loop Back To Start Of Array When Index Is Larger Than Array Length

I have been looking everywhere for a solution for this but I cant seem to find an answer anywhere! Maybe I'm just wording my question wrong, but how can I loop back to the start of an array if the index is larger than the array length? See my code below for an example:

// Array of colours
let colours = ["#FFBE36", "#FF6447", "#77FF47", "#D547FF", "#FF9E47", "#47DBFF", "#FF4770"];

// For each pack, a background colour from the array above is assigned. 
// However, these are fetched from a database so could be more than the 
// length of the array
var packs = document.getElementsByClassName("pack-item");
for (var i = 0, len = packs.length; i < len; i++) {
    // Here if i is larger than colours.length, loop back to start of 
    // colours array, e.g colours[8] = "#FFBE36"
    packs[i].style.backgroundColor = colours[i];
}

I hope this makes sense? Let me know if you want me to word it differently/explain in more detail!

Thanks :)

Upvotes: 5

Views: 4511

Answers (2)

Jon Baltz
Jon Baltz

Reputation: 232

You could do this with the modulo operator ( % ) like below. That would allow the counter to stay the correct length and the colors would stay in order.

// Array of colours
let colours = ["#FFBE36", "#FF6447", "#77FF47", "#D547FF", "#FF9E47", "#47DBFF", "#FF4770"];

// For each pack, a background colour from the array above is assigned. 
// However, these are fetched from a database so could be more than the 
// length of the array
var packs = document.getElementsByClassName("pack-item");
for (var i = 0, len = packs.length; i < len; i++) {
    // Here if i is larger than colours.length, loop back to start of 
    // colours array 
    packs[i].style.backgroundColor = colours[i % colours.length];
}

Upvotes: 6

Grant Herman
Grant Herman

Reputation: 973

Its easier to do with a while loop so you have the colorPointer that you increment and if it is equal to the colors.length-1 which is the true length of the array since it is zero indexed it will go back to the beginning.

// Array of colours
let colours = ["#FFBE36", "#FF6447", "#77FF47", "#D547FF", "#FF9E47", "#47DBFF", "#FF4770"];

// For each pack, a background colour from the array above is assigned. 
// However, these are fetched from a database so could be more than the 
// length of the array
let counter = 0;
let colorPointer = 0;
var packs = document.getElementsByClassName("pack-item");
while(counter < packs.length) {
  // Here if i is larger than colours.length, loop back to start of 
    // colours array 
    packs[counter].style.backgroundColor = colours[colorPointer];
    counter++;
    colorPointer++;
    if(colorPointer === colours.length-1){
      colorPointer = 0;
    }
}

Upvotes: 0

Related Questions