Running a google search for the word anagram you will see that an anagram is..

a word, phrase, or name formed by rearranging the letters of another, such as cinema, formed from iceman

For this blog entry I am going to do a walk through of how to create a javascript function that takes an argument of two words and returns true if the words are anagrams and false if not. For my solution to this problem I will be creating an object that is named word that will count how many times each letter of the first argument occurs. When we have the number of times each letter occurs we can then subtract the letters of the second argument, if there are no letters left over that will mean that the two words contained the exact same letter, meaning it meets our requirements for being an anagram! So let’s dive right in!

function anagram(s, t){let word ={}for (let i = 0; i < s.length; i++){
let letter = s[i]
if(word[letter]){
word[letter] = word[letter] + 1
}else{
word[letter] = 1
}

The above code snippet is creating the word object that I mentioned earlier that will count the occurrence of each letter of the first argument. If you were to return the word object it would look something like this

{ i: 1, c: 1, e: 1, m: 1, a: 1, n: 1 }

Now that we have the occurrence of each letter in the first word, it’s time to subtract the letters of the second word from the first word

for (let i = 0; i < t.length; i++){
let letter = t[i]
if (word[letter]){
word[letter] = word[letter] - 1
}else{
return false
}

As you can see every time the letter exists in in our word object we are subtracting 1. If the letter does not exits in the word object our function returns false. Now its time to put it all together!

function anagram(s, t){if(s.length !== t.length) return falselet word ={}for (let i = 0; i < s.length; i++){
let letter = s[i]
if(word[letter]){
word[letter] = word[letter] + 1
}else{
word[letter] = 1
}
}
for (let i = 0; i < t.length; i++){
let letter = t[i]
if (word[letter]){
word[letter] = word[letter] - 1
}else{
return false
}
}
return true
}

I added a condition and the top of the function that checks if he two words are the same length (because obviously if they are different lengths they aren’t anagrams lol). I also added the final return where if all the conditions are met in our function it will return true. The function is working perfectly! Not only is it working but it extremely fast and efficient!