JavaScript if statement can be used to evaluate two variables that have the same values

I am currently working on a Wordle-style game with a 6x6 grid. I'm sending the row as an array through a socket, and while I can check if a letter is correct, I'm having trouble with identifying duplicates that are in the wrong position. I iterate through the array to compare letters and their positions, but the verification process isn't working as expected. The word for this game is "cancer," and I've provided the code below. Any assistance would be greatly appreciated.

dupCheck == wordPoint
socket.on('check wordle', (check) => {
        var word = "cancer";
        var feedback = [];

        console.log(check)

        for(var i = 0; i < check.length; i++)
        {
            var letter = check[i];
            var wordPoint = word.substring(i, i+1);
            
            if(word.includes(letter))
            {
                if(letter == wordPoint)
                {
                    feedback.push("green");
                }
                else
                {
                    var duplicate = false;
                    
                    for(var j = i; j < check.length; j++)
                    {
                        var dupCheck = check[j];
                        console.log(dupCheck + " j " + wordPoint)
                        if(dupCheck == wordPoint)
                        {
                            duplicate = true;
                            console.log(j)
                            console.log("j")
                            break
                        }
                        else
                        {
                            console.log("It reads this")
                        }
                        console.log(duplicate)
                    }

                    for(var k = 0; k < i; k++)
                    {
                        var dupCheck = check[k];
                        console.log(dupCheck + " k " + wordPoint)
                        if(dupCheck == wordPoint)
                        {
                            duplicate = true;
                            console.log(k)
                            console.log("k")
                            break
                        }
                    }
                    
                    if(duplicate)
                    {
                        feedback.push("grey");
                    }
                    else
                    {
                        feedback.push("yellow");
                    }
                }
            }
            else
            {
                feedback.push("grey");
            }

        }

        console.log(feedback)
        
        io.emit('wordle feedback', feedback);
    })

During testing in the console output, I notice that the two values are indeed identical.

Answer №1

While I may not be knowledgeable about the specific details of setting up and invoking a socket, I did notice that there is an anonymous function at the core of your code snippet. In response, I have crafted a similar function below which conducts essential comparisons and outputs "grey", "yellow", or "green" based on each character of a guessed word:

const target ="cancer";

function checkGuess(test){
 const t=target.split("");
 return test.split("").map((char,index)=>{ let pos;
  if(char==t[index]) {
   t[index]="*";
   return "green";
  } else if ((pos=t.indexOf(char))>-1) {
   t[pos]="*";
   return "yellow";
  } else return "grey";
 })
}
["jackal","jacket","saucer"].forEach(test=>
console.log(test,checkGuess(test)))

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

Assess php associative array immediately

Currently, I am extracting the f-number from JPEG images through EXIF data. In order to obtain the desired number, I need to assess an expression. My current approach involves using three lines of code for this process. Is it possible to shorten this metho ...

Retrieve information from the index resource using AJAX

I feel like I might be overcomplicating things, but basically, I'm trying to retrieve all the data from an index resource and have it load when a button is clicked using AJAX. I've been using a serializer to tidy up the JSON. Both "/categories" ...

Compose an email without the need to access the website

Is there a way to send email reminders to users without having to load the website pages? In the reminder section, users can select a date for their reminder and an email will be automatically sent to them on that date without requiring them to access the ...

Problem encountered while attempting to combine multiple arrays using array_merge

Before delving into the code, let me showcase the current array hierarchy representation Array ( [Details] => Array ( [0] => Array ( [0] => stdClass Object ( ...

Delay in displaying Promise API call in NextJS

Currently, I am encountering an issue while making calls to an API function that I have already set up and confirmed to work flawlessly in other projects. Interestingly, I have utilized the same backend API calling method in another project as well as with ...

The nodemailer module in Node.js encountered an issue while trying to send an email, resulting

Looking to confirm registration, I want to send an email from my server (kimsufi). To accomplish this, I am utilizing nodemailer which can be found at https://github.com/andris9/Nodemailer Encountering the following error: Error occurred Sendmail exited ...

Troubleshooting issue: JSON object is returning undefined despite its presence in NASA API integration with ReactJS

{this.imageRenderer(item.data[0].media_type, item.links[1], item.links[0])} When trying to access item.links, it shows as undefined even though it is present. (Data is retrieved from NASA API) Image: As seen above, the links attribute exists. I am puzzle ...

Script tag for Next.js reloading functionality

I have been facing a challenge while trying to integrate third-party commenting scripts like (disqus, remark42, hyvor) into my next.js application. The issue I encountered is that the script only loads on the initial page load. Subsequently, I need to refr ...

Using Node.js to Merge the Responses of Two Results

Here is the code snippet for fetching a list of users associated with a particular ID from this service.ts file. async getId(id: number) { // Code to retrieve participants list based on ID let participants = await this.participantRepo.findById( ...

What is the reason that when a <div> click on a mobile device includes a jQuery ('#item').fadeOut() function, the CSS of the '#item' element maintains its previous hover state

While creating a mock back to top button, I encountered an issue with my jQuery call to fadeOut() behaving differently on mobile devices (this discrepancy can be observed using any desktop browser simulator). You can find the source code here: https://cod ...

Function that can be shared between two separate jQuery files

Let's say I have two separate jQuery files, both containing the same function. I would like to create a common file where I can store this shared function and then import it into other files. For example: first.js file : window.addEventListener(&apo ...

Issue with Vue.js app display within Chrome extension

I have encountered an issue while trying to run a Vuejs app in a Chrome extension as a new tab. The app renders perfectly fine when running it from the dist/ folder using simplehttpserver dist/. However, when I attempt to load the dist folder as a Chrome E ...

Having trouble with JSFIDDLE not functioning properly on my website

I'm having an issue with implementing a JSFIDDLE on my web form. The fiddle itself is working perfectly fine, but for some reason, I can't get it to work on my page. Can someone please help me figure out what mistake I might be making? Here is th ...

Issue with AngularJS toggle being obstructed by Math operation

I am facing an issue with my table rows where cells are being filled with words from an API. I have implemented a feature that allows users to toggle the selection of a cell. To achieve this, I am using ng-class={selected:toggle} and ng-click="toggle = !to ...

"Getting an 'Undefined index' error while accessing a JavaScript variable in PHP

Every row in my table contains an Edit button. I managed to fetch the row number by clicking on the Edit button using JavaScript, but I am unsure how to do it in PHP. My attempt to pass the variable from JS to PHP resulted in an error: Undefined index ...

Creating a fresh shortcut on the selenium IDE

Is there a way to customize shortcuts in Selenium IDE by modifying its code? For instance, I would like to set the shortcut ctrl + p for the action run test case, similar to how the save action is assigned ctrl + s. I've searched for the JavaScript ...

What is the best way to invoke a function using a string as its name?

In my grid configuration function, I am assigning column definitions. One key, valueGetter, requires a function to be called to fetch the column value. The issue I am encountering is that the API returns this value as a string. When I try to set it using ...

Generate a fresh collection of objects all sharing a common identifier within a given array

Looking for help transforming this schedules array to match the desired output. Any ideas? let schedules = [ {day: 'Sunday', time: '5:00 PM'}, {day: 'Monday', time: '4:00 PM'}, {day: 'Monday', time: &ap ...

Add design to the footer during a specific event using Javascript

Here is the CSS code I am working with: .footer { font-family: "lato", sans-serif; padding: 20px; line-height: 1.2; text-align: right; background: #eee; color: #0D47A1; font-size: 13px; height: 80px; position: fixed; right: 0px; botto ...

Alerting JavaScript with element Selector doesn't function at full capacity

I am currently implementing Notify JS from the following source : Below is the HTML code I am using: <div> <p><span class="elem-demo">aaaa</span></p> <script> $(".elem-demo").notify( "Hello Box" ...