0

Why isn't this code correctly pushing words to the answer array? When I change the loop to:

    for (var k in testDict) {
        console.log(testDict[k].split("").sort());
    }

it correctly prints what I'm expecting, an array of split, sorted characters from the words. So I'm not sure why it's not evaluating to equal and pushing to answer. Thanks!

function word_unscrambler(word, dict) {
    var testDict = dict;
    var answer = [];
    var word_scrambled = word.split("").sort();
        for (var k in testDict) {
            if (word_scrambled === testDict[k].split("").sort())
                answer.push(testDict[k]);
        }
    console.log(answer);
}

word_unscrambler("kevin", ["trees", "but", "ankle", "nevik", "knive", "evin"]);
0

3 Answers 3

3

The problem is that you are testing the arrays for equality, since you are working with strings, you can just join both arrays being compared:

function word_unscrambler(word, dict) {
    var testDict = dict;
    var answer = [];
    var word_scrambled = word.split("").sort().join('');
        for (var k in testDict) {
            if (word_scrambled === testDict[k].split("").sort().join(''))
                answer.push(testDict[k]);
        }
    console.log(answer);
}
Sign up to request clarification or add additional context in comments.

3 Comments

+1. Might as well memoize word_scrambled.join('')
Awesome, much appreciated
@Jacob Krall That's true, edit'd
1

You can not compare arrays by using == See this page for more info and a solution for your problem: How to check if two arrays are equal with JavaScript?

Comments

0

You can't compare arrays for equality directly, since it will only compare their pointers. You must compare the contents of the arrays instead. As long as you're not dealing with multi-dimensional arrays, this should be sufficient:

function word_unscrambler(word, dict) {
    var testDict = dict;
    var answer = [];
    var word_scrambled = word.split("").sort();
        for (var k in testDict) {
            if (arrays_equal(word_scrambled, testDict[k].split("").sort()))
                answer.push(testDict[k]);
        }
    console.log(answer);
}

function arrays_equal(arr1, arr2) {
    for (var i in arr1) {
        if (arr1[i]!==arr2[i])
            return false;
    }
    return true;
}

word_unscrambler("kevin", ["trees", "but", "ankle", "nevik", "knive", "evin"]);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.