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");
}
}
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");
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With