Checking for string anagrams JavaScript


Anagrams are those string pair, one of which when reordered in a certain pattern yields the other one.

For example −

'hello' and 'lolhe' are anagrams because we can reorder 'lolhe' to form the string 'hello' or vice-versa.

We are required to write a JavaScript function that takes in two strings, say str1 and str2. The function should return true if the strings are anagrams of each other, false otherwise.

We can create a map that tallies the number of characters for each input string. Then, we can compare the maps to see if they are identical.


const str1 = 'hello';
const str2 = 'lolhe';
const charCount = string => {
   const table = {};
   for (let char of string.replace(/\W/g, "").toLowerCase()) table[char] = table[char] + 1 || 1;
   return table;
const anagrams = (stringA, stringB) => {
   const charCountA = charCount(stringA); const charCountB = charCount(stringB);
   if (Object.keys(charCountA).length !== Object.keys(charCountB).length)
      return false;
      for (let char in charCountA)
      if (charCountA[char] !== charCountB[char])
         return false;
      return true;
console.log(anagrams(str1, str2));


And the output in the console will be −