0

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 ?

2 Answers2

0

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];
});
Matěj Koubík
  • 1,087
  • 1
  • 9
  • 25
0
let wordsForTheGame = ['red', 'blue', 'yellow', 'orange', 'green', 'black', 'aqua', 'gray', 'purple'];
let alreadyUsed = [];

const randomColor = () => {
   return wordsForTheGame.filter(word => !alreadyUsed.includes(word))[Math.floor(Math.random() * items.length)];
}

batons.forEach(btn => {
    const color = randomColor();
    alreadyUsed.push(color)
    btn.style.backgroundColor = color;
});