Marco Pereira Marco Pereira - 3 months ago 12
Javascript Question

Check for Anagram in 2 strings

i created a function that checks if 2 words are anagrams, but i wish to made it better, i feel the declarion of the counter after in the if statement is not quite well, if anybody have a better solution would be great.

function checkAnagram(string1, string2){

if(string1.length !== string2.length){
return false;
}

for(var i = 0; i < string1.length; i++){

if(count <= 0){

return false;
}
var count = 0;

for(var t = 0; t < string2.length; t++){

//counter = 0

if(string2[t].toLowerCase() == string1[i].toLowerCase()){
//counter++;
count++;
break;
}


}

}

return true;
}

Answer

Here is a much easier way of doing it:

var s1 = "test"
var s2 = "tset"

function testAnagram (s1, s2){

 if(!s1 || !s2 || s1.length !== s2.length){return false;}

 var lS1 = s1.toLowerCase();
 var lS2 = s2.toLowerCase();

 if(lS1 === lS2) {return false;}

 var rS1 = lS1.split('').sort().join('');
 var rS2 = lS2.split('').sort().join('');

 return rS1 === rS2;
}



var result = testAnagram(s1, s2);

alert(result);