JS Algorithm – Anagrams

Lake Louise, Canada by https://unsplash.com/@keano16

Check to see if two provided strings are anagrams of each other. One string is an anagram of another if it uses the same characters in the same quantity. Only consider characters, not spaces or punctuation. Consider capital letters to be the same as lower case.

By definition an anagram is a play on words created by rearranging the letters of the original word to make a new word or phrase, like: Tar = Rat

Examples for this exercise
anagrams(‘rail safety’, ‘fairy tales’) –> True
anagrams(‘RAIL! SAFETY!’, ‘fairy tales’) –> True
anagrams(‘Hi there’, ‘Bye there’) –> False

First solution:

// Function to check if 2 string are anagrams of each other
function anagrams(stringA, stringB) {
  // Converting each string in object format
  // to know how many times a letter is found in the string
  const aCharMap = buildCharMap(stringA);
  const bCharMap = buildCharMap(stringB);


  // If the keys length of each object is different of another
  if (Object.keys(aCharMap).length !== Object.keys(bCharMap).length) {
    // then are not anagram
    return false;
  }

  // Go through every node of the object
  for (let char in aCharMap) {
    // If some value of each key of the object
    // is different from the other value of the object
    if (aCharMap[char] !== bCharMap[char]) {
      // then are not anagram
      return false
    }
  }

  // Then return true means that are anagrams
  return true;
}


// Helper function for convert a string into a object
// and count how many times a letter is found in the string
// example: 'xxxxx' -> { x: 5 } so the letter x is found 5 times
function buildCharMap(str) {
  let charMap = {};

  // Go through every character in the string
  // deleting the spaces in the string all the spaces and converting to lower case
  for (let char of str.replace(/[^\w]/g, "").toLowerCase()) {
    charMap[char] = charMap[char] + 1 || 1;
  }

  // Return the string converted in object
  // example: 'xxxxx' -> { x: 5 }
  return charMap;
}

anagrams('Hi there', 'Bye there')

Result:

If we run the code with this strings anagrams(‘rail safety’, ‘fairy tales’)

Result:

Second solution:

function anagrams(stringA, stringB) {
  // If the strings are identical, Then is anagram
  return cleanString(stringA) === cleanString(stringB)
}

// Helper function to ordered a string
function cleanString(str) {
  // removing all the spaces
  // converting the string to lower case
  // converting the string into an array
  // using the .sort() method to order the array
  // converting that array to string again (this will give us
  // an alphabetically ordered string) -> abcde...
  return str.replace(/[^\w]/g, "").toLowerCase().split('').sort().join('');
}

anagrams('rail safety', 'fairy tales');

Result:

By Cristina Rojas.