Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why doesn't this code work for anagram checking?

I'm trying make an anagram check in javascript. For simplicity, assume that the function below only takes lowercase strings without any spacing/numbers/symbols. Why doesn't the code below work?

var anagram = function(string1, string2) {
    var string1array = string1.split('').sort();
    var string2array = string2.split('').sort();
    if (string1array == string2array) {
        console.log("they're anagrams");
    }
    else {
        console.log("they are not anagrams");
    }
}
like image 528
d1du Avatar asked May 31 '26 18:05

d1du


1 Answers

The == does not work for Array, as Array is an Object. The == operator checks if the Objects are the SAME:

var foo = {};
var bar = {};
console.log(foo == bar); // false
var foo2 = {};
var bar2 = foo2;
console.log(foo2 == bar2); // true

Thus, the simplest was to check this is to convert them back into String and use ==, since == does work with String:

var anagram = function(string1, string2) {
    var string1array = string1.split('').sort();
    var string2array = string2.split('').sort();
    // All I used was .join('') on both.
    if (string1array.join('') == string2array.join('')) {
        console.log("they're anagrams");
    }
    else {
        console.log("they are not anagrams");
    }
}
like image 187
Andrew Templeton Avatar answered Jun 03 '26 06:06

Andrew Templeton