Search code examples
javascriptarrayscolorsrepeat

applying colors from array to buttons without repetition?


I'm trying to apply an array of colors

let wordsForTheGame=['red','blue','yellow','orange','green','black','aqua','gray','purple'];

exactly to 9 button elements. I use this function to shuffle:

function shuffleArray (arr) {
    for (let i = arr.length - 1; i > 0; i--) {
      let j =  Math.floor(Math.random() * Math.floor(arr.length - 1));
      [arr[i], arr[j]] = [arr[j], arr[i]];
    }
    return arr;
  }

and this to append colors to buttons:

batons.forEach(btn => {
    btn.style.backgroundColor = shuffleArray(wordsForTheGame)[0];
});

Yet, the colors are still repeating.

How can I make this function append colors to all the buttons , so they won't repeat and there will be no duplicated color on 2 or more buttons ?


Solution

  • You are shuffling the array again for each button. Shuffle it just once on the beginning and then use the same shuffled array for all the buttons.

    const shuffledArray = shuffleArray(wordsForTheGam);
    
    Object.keys(batons).forEach(key => {
        batons[key].style.backgroundColor = shuffledArray[key];
    });