JSFiddle - React, Tailwind, and code Playground
JavaScript
/**
* ******************************************************************************************
* Get the correct color
* ******************************************************************************************
*/
function mixColors(colorsArray) {
// Create an object to store the mixed color
const mixedColor = {
r: 0,
g: 0,
b: 0,
};
// Loop over the first 3 colors in the array
colorsArray.slice(0, 3).forEach((color) => {
// Get the RGB values of the color
const colorValues = color
.replace("rgb(", "")
.replace(")", "")
.split(", ")
.map((value) => parseInt(value));
// Add and count the RGB values par each letter to the object
mixedColor.r += colorValues[0];
mixedColor.g += colorValues[1];
mixedColor.b += colorValues[2];
});
// Divide the RGB values by 3
mixedColor.r = Math.floor(mixedColor.r / 3);
mixedColor.g = Math.floor(mixedColor.g / 3);
mixedColor.b = Math.floor(mixedColor.b / 3);
return `rgb(${mixedColor.r}, ${mixedColor.g}, ${mixedColor.b})`;
}
// Display the correct color
let mixedCorrectColor = document.getElementById("mixedCorrectColor");
mixedCorrectColor.style.backgroundColor = mixColors(colorsArray);