This is a new challenge I'm facing with my JavaScript bingo game, building off of previous assistance I received.
In my bingo game, I've implemented a method that stores the drawn balls in an array called ballsDrawn. After confirming that ballsDrawn does indeed contain all the drawn numbers in the game, I'm now working on a method to validate whether the marked spaces on the bingo card match the drawn balls. Before acknowledging a Bingo claim, I want to cross-check all the marked spaces against the drawn numbers, filtering out any potential cheating attempts where incorrect spaces are marked. Once I have the legitimately marked spaces, I'll determine if there's a valid Bingo.
To verify the spaces, I select all marker elements (querySelectorAll) and filter out only the marked ones. I then extract the number from each element's textContent and gather them in markedSpaces, which works smoothly. Subsequently, I utilize Array.filter() and .includes to compare each number in markedSpaces with those in ballsDrawn. If there's a match, I add it to the legitSpaces constant and log the result.
While testing the game in my browser, the console.log output for legitSpaces indicates an empty array, contrary to JSFiddle results with identical data. It puzzles me why there's a discrepancy and why my code fails to populate legitSpaces as expected.
Here's the key section of the JavaScript code:
const checkIfMarksAreCorrect = () => {
const spaces = document.querySelectorAll(".marker");
const markedSpaces = Array.from(spaces)
.filter((space) => space.classList.contains('marked'))
.map((markedSpace) => markedSpace.textContent.trim());
console.log('The marked spaces are: ' + markedSpaces);
console.log(`checkIfMarksAreCorrect ballsDrawn: ${ballsDrawn}`);
const legitSpaces = Array.from(markedSpaces)
.filter((markedNumber) => ballsDrawn.includes(markedNumber));
console.log('legitSpaces: ' + legitSpaces);
};
The outputs of the three console.logs within this latest method execution are as follows:
The marked spaces are: 10,12,30,23,34,75
checkIfMarksAreCorrect ballsDrawn: 10,52,40,29,32,23,13,46,45,75,34,70,4,3,16,66,30,60,28,12
legitSpaces:
I ran the following code snippet in JSFiddle:
const ballsDrawn = [10,52,40,29,32,23,13,46,45,75,34,70,4,3,16,66,30,60,28,12];
const markedSpaces = [10,12,30,23,34,75];
const legitSpaces = Array.from(markedSpaces)
.filter((markedNumber) => ballsDrawn.includes(markedNumber));
console.log(`legitSpaces: ${legitSpaces}`);
And received this console.log output:
"legitSpaces: 10,12,30,23,34,75"
Any guidance would be highly appreciated.