Issue with populating an array in code using JavaScript's Array.filter, but working fine in JSFiddle

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.

Answer №1

Appreciation to all for sharing your feedback. Taking into account the suggestions, I have integrated the following line into my code:

const markedSpaceNumbers = markedSpaces.map(Number);

As a result, my method now appears as follows:

const verifyMarkedSpaces = () => {
    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(`verifyMarkedSpaces ballsDrawn: ${ballsDrawn}`);
    const markedSpaceNumbers = markedSpaces.map(Number);
    const legitSpaces = markedSpaceNumbers
        .filter((markedNumber) => ballsDrawn.includes(markedNumber));
    console.log('legitSpaces: ' + legitSpaces);
};

Excited to report that everything is functioning perfectly now! Many thanks once more!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Exploring the power of hierarchical organization in node.js modules

One of my modules is called UserProvider and it has the following structure: var UserProvider = function(db) { ... } UserProvider.prototype.createUser = function(email, password, callback) { ... } UserProvider.prototype.findUserByEmail = function(email, c ...

Guide on enforcing form validation with the utilization of a for loop in conjunction with an error array

When I click a button, I want to validate input fields for emptiness. Specifically, I am filtering an array to check if any of the inputs are empty. My goal is to add an error message to the array only for those inputs that are empty. However, the issue I& ...

Explicitly linking controllers with Angular scope objects

According to the documentation on AngularJS Understanding controllers: Linking Controllers to Angular Scope Objects Controllers can be linked to scope objects implicitly through the ngController directive or $route service. These two methods are commo ...

Different conversations are taking place concurrently. How can we determine which one is currently being attended to

In my application, multiple dialogs are open simultaneously, each with its own set of shortcuts. It is important to ensure that these shortcuts work correctly based on the focused dialog. Is there a way to determine which dialog is currently in focus? Ed ...

Tips for connecting a Django API project with a nodejs and react frontend

I'm currently working on a Django API project and I am considering incorporating Node.js into the mix. Additionally, I am interested in using React for the frontend of the application. Is this combination of technologies feasible? Would it be advisabl ...

Ways to establish a condition in the absence of any data

I need a search box for users to look up a name in the database. The main goal is to locate the name if it exists, display "not available" if it doesn't, and not take any action if no data is inputted. PHP File -- // url- "/userdata/mydata" public ...

Retrieve information from a template and pass it to a Vue component instance

Being a newcomer to vue, I have a fundamental question. In my template, I have a value coming from a parsed object prop like this: <h1>{{myval.theme}}</h1> The above code displays the value in the browser. However, I want to store this value i ...

Having trouble accessing the routes I've set up

I've been working on my Express.js project and I'm having trouble setting up routes. I want 'localhost:9000/users' to display 'User List', but instead, it's showing 'Cannot GET /users'. I attempted moving the co ...

Set an enumerated data type as the key's value in an object structure

Here is an example of my custom Enum: export enum MyCustomEnum { Item1 = 'Item 1', Item2 = 'Item 2', Item3 = 'Item 3', Item4 = 'Item 4', Item5 = 'Item 5', } I am trying to define a type for the f ...

Why isn't the Full Calendar loading automatically within a Bootstrap Tab?

I have been working on a travel website and incorporated a bootstrap tab feature. In the first tab, I have some content, while in the second tab, I've added a full calendar with JavaScript. Everything seems to be functioning correctly when the full ca ...

Enhancing MaterialUI Card in React with custom expandable feature: learn how to dynamically change Card styles on expansion

There are a total of 20 cards displayed on this page. When using MaterialUI Card, the onExpandChange property allows for defining actions like this: <Card expandable={true} onExpandChange={this.clickHandle}> With this action, it is easy to deter ...

In React, what distinguishes the use of spread props before or after className in a span element?

Hey there! I'm new to the world of React and javascript development, and I'm curious about understanding the distinction between var a = { className: 'my-secondary-classname' }; <span className="my-span-classname" {...a}&g ...

What does dist entail?

I am currently utilizing gulp to create a distribution folder (dist) for my Angular application. After consolidating all the controllers/services JS files and CSS, I am now faced with handling the contents of the bower folder. In an attempt to concatenat ...

Discover the Elements that have been incorporated through the use of JavaScript

I am facing an issue with my ASP site where users can add Label elements. The problem is I am not able to track the labels that were added or their IDs. All I know is that they will be inside the Panel called pnl_Added. Once the user has finished adding la ...

The parameter type 'Function' cannot be assigned to the parameter type 'ComponentType<never>'

Having an issue passing a component to the connect method from react-redux. The error message I'm receiving is as follows: Argument of type 'Function' is not assignable to parameter of type 'ComponentType'. Type 'Function&ap ...

"Exploring the Art of Showcasing Duplicate Image Count from User Input in an

I need to showcase multiple duplicates of 2 different images on a webpage. Users are asked for the duplication speed, which I have already implemented, and also how many copies of each image they want. function show_image() { var img = document.create ...

The async/await loop functions properly when using axios.get, but encounters issues when trying to fetch data from a local .json file

I am curious about the aspects of JavaScript (specifically regarding async/await) that I might be overlooking. I believe this question is unique and not a duplicate. Due to the complexity of my code, I will describe it instead of providing an example. The ...

Apply a border to the navbar when it hovers over a selected element

export const NavBar = () => { return <div className="navbar">this is navbar</div>; }; const Content = () => { return ( <div className="main"> <div className="background"> some content </div> ...

How can union types be used correctly in a generic functional component when type 'U' is not assignable to type 'T'?

I've been researching this issue online and have found a few similar cases, but the concept of Generic convolution is causing confusion in each example. I have tried various solutions, with the most promising one being using Omit which I thought would ...

What is the best way to rearrange DOM elements using the output of a shuffle function?

Looking for a solution to shuffle and move around cards in an HTML memory game? Let's analyze the current setup: <ul class="deck"> <li class="card"> <i class="fa fa-diamond"></i> </li> ...