I am trying to create an array of nine random words. Each word should have a color key value. Out of the nine words 3 words should have the color 'red', 3 words should have the color 'blue', and one word shoule have the color 'black'. The color needs to be assigned to the word randomly (each time the array is produced the positioning of the each color should change randomly).
My code so far produces and array of words each randomly assigned a color however with no limit - for example I may get 2 black 3 red and 4 blue. Then the next time 0 black 4 red and 5 blue. I need to produce 4 red 4 blue and 1 black every time (randomly positioned).
I thought that a counter would be useful however currently is not being used.
Any help would be great - I am new to coding so be critical!
Here is my code:
//Globals
const wordList = [..... ***remov
ed giant list of words from post***
];
const colorList = ['red', 'blue', 'black']
let randomWordNum = Math.floor(Math.random()*(wordList.length))
let randomColorNum = Math.floor(Math.random()*(colorList.length))
let coloredWords = [];
let redCounter = 0;
let blueCounter = 0;
let blackCounter = 0;
//Square function
//assigns color and word value to object key
//pushes object to new array 'words'
const createSquare = () => {
let randomWordNum = Math.floor(Math.random()*(wordList.length))
let randomColor = colorList[Math.floor(Math.random()*(colorList.length))]
if (randomColor === 'red') {
redCounter++
} else if (randomColor === 'blue') {
blueCounter++
} else if (randomColor === 'black') {
blackCounter++
}
var square = {
color: randomColor,
word: wordList[randomWordNum],
}
coloredWords.push(square)
console.log(square)
}
//Loops through above function until the array is x values
const wordArr = () => {
while (coloredWords.length < 9 ){
createSquare()
}
}
wordArr()
console.log(coloredWords)