0

I'm trying to check a submitted string against a letterset. If word_string = "GAR", this should return "GAR" because these letters appear in letterset.

For some reason, some words appear correctly, and some appear with missing letters. For example, with word_string = "RAG", this returns "R". "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);

            } 
        }

}
10
  • 2
    Why isn't letterset an array? Why are you calling .splice() with only one argument, and have you thought about what happens if you remove elements from an array while you're iterating over that same array? What do you think that does to your for loop's indexing? Commented Jun 20, 2015 at 4:21
  • can you post a jsfiddle that is working with the current example? Commented Jun 20, 2015 at 4:23
  • Because it's coming from a python backend as a json object Commented Jun 20, 2015 at 4:23
  • what is word? var word = document .getElementById('word_container') .childNodes; Commented Jun 20, 2015 at 4:25
  • word is the html element with the necessary string as its .innerHTML Commented Jun 20, 2015 at 4:27

1 Answer 1

2

I think you are using splice incorrectly, regardless this is a bit over complicated try:

 for (var i in word) {
    var w = word[i].innerHTML;
    if (ls.indexOf(w)> -1) {
            word_string += w;
        } 
    }
Sign up to request clarification or add additional context in comments.

1 Comment

FYI this ls.indexOf(w)> -1 is kind of like x in list in python.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.