This is another issue related to my JavaScript bingo game and a follow-up to something I received help with.
In my bingo game, I have a method that saves balls that were drawn to an array (ballsDrawn). I have verified that ballsDrawn does in fact get populated with all the balls that have been drawn in the game.
I am working on a method to verify that all the spaces marked on the bingo card do in fact match balls that were drawn. If a person is claiming they have Bingo, I first want to check all the marked spaces to see if the numbers on those spaces match the numbers of the balls drawn. I am trying to filter out any spaces that don’t match, in case the player marked spaces on their card to try and cheat. Once I have all the spaces that are in fact legitimately marked, I will figure out some way to see if they have a bingo.
To check the spaces I first grab all the spaces (querySelectorAll) and then filter so that I only have the ones that are marked. I then get the textContent of those elements to get the number of the space, which I put in markedSpaces. That part is working correctly. I am then using Array.filter() and .includes to see if each number in markedSpaces is in ballsDrawn. If it is, it should be added to the const legitSpaces. I then have a console.log of legitSpaces.
When I am running the game in my browser, the console.log for legitSpaces makes it appear that legitSpaces is empty. However, if I take the numbers from that game for ballsDrawn and markedSpaces and run the code in JSFiddle, it appears that legitSpaces is populated. I’m not sure why the results are different and why legitSpaces is not populating in my code.
Here is the relevant portion of the JavaScript:
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 results for the three console.logs in the methods in my latest code run 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 put the following 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 got the following console.log:
“legitSpaces: 10,12,30,23,34,75”
Any help is appreciated.