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
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);
function checkAnagram(string1, string2) {
return string1.replace(/[^\w]/g,'').toLowerCase().split('').sort().join('') ===
string2.toLowerCase().replace(/[^\w]/g,'').split('').sort().join('')
}
If you don't want to use prebuild methods like .split() .sort() .join() then
function isAnagrams(stringA, stringB) {
// just to remove special char and convert it to lowercase
stringA = stringA.replace(/[^\w]/g, "").toLowerCase();
stringB = stringB.replace(/[^\w]/g, "").toLowerCase();
if (stringA.length !== stringB.length) return false;
let aCharMap = {};
let bCharMap = {};
/*
making of mapObject of both string, containing character as property and
count of that character as value
*/
for (let i = 0; i < stringA.length; i++) {
bCharMap[stringB[i]] = bCharMap[stringB[i]] + 1 || 1;
aCharMap[stringA[i]] = aCharMap[stringA[i]] + 1 || 1;
}
// checking both CharMap value
for (let q of stringB) {
if (bCharMap[q] !== aCharMap[q]) {
return false;
}
}
return true;
}
console.log(`isAnagram : ${isAnagrams('rail safety', 'fairy tales')}`)
so if you pass isAnagrams('rail safety','fairy tales');
then character map will look like this
aCharMap = { r: 1, a: 2, i: 1, l: 1, s: 1, f: 1, e: 1, t: 1, y: 1 }
bCharMap = { f: 1, a: 2, i: 1, r: 1, y: 1, t: 1, l: 1, e: 1, s: 1 }
then we will compare if they have same value or not based on that result will be decided
Your code returns true for strings 'aabb' and 'abcc', which are not anagrams. You can just sort the strings and check if they're equal:
function checkAnagram(string1, string2) {
return string1.toLowerCase().split("").sort().join("") === string2.toLowerCase().split("").sort().join("")
}