I'am building a casino game and ran into a problem. I have this code:
let images = [
document.getElementById("img1"),
document.getElementById("img5"),
document.getElementById("img9"),
document.getElementById("img11"),
document.getElementById("img13")
]
let sources = ["cherry.png", "lemon.png", "watermelon.png", "grape.png", "diamond.png",
"luckycharm.png"]
So what I want to do here is to check if atleast 3 images has the same source. How can I do it?
CodePudding user response:
You can get the "src" attribute of a image using the .getAttribute("src") method, then you can compare them in JavaScript as strings.
In your case, that would look like:
images[0].getAttribute("src") === images[1].getAttribute("src")
Which could be: "cherry.png" === "lemon.png"
and this would return false.
CodePudding user response:
I thinks creating an object with keys (image names) and values (array of dom elements that have the image) is a good approach for this application. You may want to know which image appears where.
let sources = ["cherry.png", "lemon.png", "watermelon.png", "grape.png", "diamond.png",
"luckycharm.png"]
const images = ["cherry.png","cherry.png","watermelon.png","cherry.png","diamond.png"];
const makeChunks = () => {
const chunks = {};
images.forEach(
(img, i) => img in chunks ? chunks[img].push(i) : chunks[img] = [i]
);
return chunks;
}
console.log(makeChunks())
const findTrio = () => {
return Object.fromEntries(
Object.entries(makeChunks()).filter((x) => x[1].length > 2)
)
}
console.log(findTrio())