I've created a function that checks if 2 words are anagrams, but I want to make it better. I feel the declaration 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;
}
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);
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