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"]);
try-catch-finally
  • 7,436
  • 6
  • 46
  • 67
Kevin Banas
  • 191
  • 2
  • 3
  • 13

3 Answers3

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);
}
Nick Beeuwsaert
  • 1,598
  • 1
  • 11
  • 18
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?

Community
  • 1
  • 1
Jordi Jolink
  • 461
  • 3
  • 7
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"]);
Michael Brook
  • 380
  • 5
  • 10