3

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");
    }
}
d1du
  • 296
  • 1
  • 3
  • 12

3 Answers3

5

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");
    }
}
Andrew Templeton
  • 1,656
  • 10
  • 13
2

You can't compare array elements directly like that in Javascript.

Here are multiple implementations that will do that: How to check if two arrays are equal with JavaScript?.

In your case, you could simply use a .join() to compare two strings instead:

var anagram = function(string1, string2) {
    var string1_sorted = string1.split('').sort().join('');
    var string2_sorted = string2.split('').sort().join('');
    if (string1_sorted == string2_sorted) {
        console.log("they're anagrams");
    }
    else {
        console.log("they are not anagrams");
    }
}
Community
  • 1
  • 1
Mr_Pouet
  • 4,061
  • 8
  • 36
  • 47
0

I'm trying make an anagram check in javascript.

Well this is not exactly an Answer to this question but a different Approach to this Problem; and in my first tests, way faster (33-50%).
Mr_Pouet and Andrew Templeton already gave you an answer to this exact question.

function anagram(a, b, caseSensitive){
    if(a.length !== b.length) return false;
    var c = caseSensitive? a: a.toLowerCase(), 
        d = caseSensitive? b: b.toLowerCase(),
        map = new Array(128),
        cc;

    for(var i = a.length; i--; ){
        cc = c.charCodeAt(i);
        map[cc] = (map[cc] || 0) + 1;

        cc = d.charCodeAt(i);
        map[cc] = (map[cc] || 0) - 1;
    }

    var i = map.length;
    if(i < 256){
        //faster for ANSI-like text
        while(i--) 
            if(i in map && map[i]) return false;
    }else{
        //faster for a huge sparse map, 
        //like UTF8 multibytes (Asian characters for example)
        for(var k in map)
            if(map[k]) return false;
    }
    return true;
}
Thomas
  • 3,513
  • 1
  • 13
  • 10