Unusual outcomes stemming from JavaScript nested for loops

In my current project, I am working on verifying a submitted string against a set of letters. If the word_string is "GAR", the expected output should be "GAR" because all these letters are found in the letter set.

However, I am facing an issue where some words are checked correctly while others are missing certain letters. For example, when the word_string is "RAG", the output is just "R". Similarly, "FIG" returns "FG".

letterset = {0: "R", 1: "A", 2: "G", 3: "A", 4: "O", 5: "E", 6: "F", 7: "I"}


    var ls = [];
    for (prop in letterset) {
        ls.push(letterset[prop]);

    };
    console.log(ls)
    var word_string = '';
    var word = document
               .getElementById('word_container')
               .childNodes;
    for (var i in word) {
        var w = word[i].innerHTML;

        for (var prop=0; prop<ls.length; prop++) {
            if (ls[prop] == w) {
                console.log(w);
                word_string += w;
                ls.splice(prop);

            } 
        }

}

Answer №1

It seems like there might be a mistake in your use of the splice method. Here is a simpler version for you to try:

 for (let char of word) {
    let w = char.innerHTML;
    if (ls.indexOf(w) !== -1) {
        word_string += w;
    }
}

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

Invoking a method in Vue.js from another component

I'm just starting out with VUE and I have a unique challenge for my project. I want to have a button on one page that triggers a function on another page. I know some may ask why not keep the button and function on the same page, but I am exploring ho ...

Jquery is not working as expected

I am having trouble implementing a jQuery function to show and hide select components. It doesn't seem to be working correctly. Can someone help me identify the issue? <html> <head> <meta charset='UTF-8' /> <script ...

utilizing the entire string rather than just a portion

I was attempting to create a JavaScript jQuery program that vocalizes numbers based on some previously saved data. However, I encountered an issue where only the last number in the sequence was being played (the final character in the string). Below is t ...

Is it possible to create Firebase real-time database triggers in files other than index.js?

Is it possible to split a large index.js file into multiple files in order to better organize the code? Specifically, can Firebase triggers be written in separate JavaScript files? If so, could you please provide guidance on how to do this properly? child. ...

Guide on setting a wait while downloading a PDF file with protractor

As I begin the download of a pdf file, I realize that it will take more than 2 minutes to complete. In order to verify if the file has successfully downloaded or not, I will need to wait for the full 2 minutes before performing any verification checks. C ...

What is the best way to show a dropdown menu list using my code and JSON response object?

I am currently working on displaying a dropdown list based on the JSON response object. How can I implement it with the code snippet below? in HTML <select class="form-control" name="productCategories[]" id="productCategories< ...

The text box remains disabled even after clearing a correlated text box with Selenium WebDriver

My webpage has two text boxes: Name input box: <input type="text" onblur="matchUserName(true)" onkeyup="clearOther('txtUserName','txtUserID')" onkeydown="Search_OnKeyDown(event,this)" style="width: 250px; background-color: rgb(255, ...

Determining the cursor location within a character in a div that is content editable using AngularJS

I am facing challenges with obtaining the cursor caret position within a contenteditable div. Currently, I am utilizing the following function : onBlurArea (field, ev) { ev.preventDefault() const editable = ev.target.childNodes[1].childNodes[2] ...

What is the most efficient method for iterating through a 2-dimensional array row by row in PHP?

I have a 2D array and I need to insert multiple data into a table using a loop. Here is the data: $data['id'] = array([0] => '1', [1] => '2'); $data['name'] = array([0] => 'Ben', [1] => ' ...

Displaying a Div element containing dynamically calculated values based on selected options in Angular

As a newcomer to Angular, I decided to challenge myself by building a simple app. Currently, my select options only display the keys of a data object. What I really want to achieve is to show a value beneath the second select box for each team, which displ ...

What are the steps to start a ExpressJS server for webpages that are not index.html?

I am exploring how to browse/run/view web pages other than just the index.html file in my public folder, which contains multiple HTML files. I am using ExpressJS and NodeJS for this purpose, but every time I start my server, I can only access the index.htm ...

How to trigger a submit action on a different page from an iframe using PHP

Is there a way to submit the iframe page using the modal's submit button in Page1.php to trigger the submit button of Page2.php? I need help executing this efficiently. The purpose of having the submit button in a modal is to perform multiple functio ...

Encountering a 403 error while trying to deploy a Node.js application on Heroku

Yesterday, I encountered an issue while trying to access a Node.js application on Heroku. The error message from the Chrome console was: Refused to load the image 'https://browser-rpg-app.herokuapp.com/favicon.ico' due to Content Security Policy ...

Unable to execute node file in Visual Studio Code's terminal

My attempt to run a file using the terminal in Visual Studio Code has hit a snag. Despite my best efforts, I keep encountering an error message that reads as follows: For example, when I type "node myfile.js" into the terminal, I get the following error: ...

Simulate a keyboard key being pressed and held for 5 seconds upon loading the page

Is it possible to create a script that automatically triggers an event to press and hold down the Space key for 5 seconds upon page load, without any user interaction? After the 5 seconds, the key should be released. It is important to emphasize that abso ...

Tips for displaying information from two separate MongoDB documents on a single webpage with the help of Mongoose and Express

Currently, I am working with NodeJS, Express, EJS, and Mongoose. While I have a good grasp on most of these technologies, I find myself navigating through the complexities of Mongoose. In my project, I have established two Models that are interconnected w ...

Navigating within a class-based component using Next.js: A brief guide

Is it possible to create a redirect from within an onSubmit call while maintaining CampaignNew as a class-based component? I have provided the code snippet below, and I am looking for guidance on achieving this. import React, { Component } from "rea ...

What is the best way to determine if the form has been submitted?

I am working on a React form and need to determine when the form has been successfully submitted in order to trigger another request in a separate form. const formRef = React.useRef<HTMLFormElement>(null); useEffect(() => { if (formRef &a ...

Assign increasing values within an array

Is there a way to efficiently update multiple values in an array by mapping through them? I want to select and change all of them simultaneously. state.formData.forEach(item => { item.EndDate = nextDayIfSelected; }); ...

Is it possible to use window.print() to print the entire contents of a DIV with both horizontal and vertical scroll bars?

In my code, I have a div that contains both horizontal and vertical scrollers. Whenever I try to print the content inside this div using the window.print() method, it only prints the visible portion of the div. Here is the code snippet that I have attempte ...