Check if given strings are an Anagram with JavaScript

·

2 min read

Check if given strings are an Anagram with JavaScript

Instructions

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.

//Examples
anagram('rail safety', 'fairy tales') --> True
anagram('RAIL! SAFETY!', 'fairy tales') --> True
anagram('Hi there', 'Bye there') --> False

Solution 1

Firstly, create a helper function to return a cleaned string. This function needs to remove any spaces and punctuation from the string. Make the string lowercase and sort alphabetically. This could also be done inline within the anagram function.

Clean both strings and compare the returned values.

const anagram = (stringA, stringB) => {
    // compare the 2 cleaned strings
  return cleanString(stringA) === cleanString(stringB)
}

const cleanString = (string) => {
    // remove spaces and punctuation. Convert to lowercase and sort string
  return string.replace(/[^\w]/g, '').toLowerCase().split('').sort().join('')
}

Solution 2

Create a helper function . Within the helper function create an empty object. Loop through each character in the string, checking if the character is in the object. If not in the object, add it with the value of 1 else plus the current value by 1.

This will return a object that looks similar to:

chars = {
    "a":1,
    "b":1,
    "c":11,
    "d":1,
}

Using the new helper function create two new variables mapping the two given strings. Now compare both object keys to ensure they are the same length. If not return false. If they do have the same number of characters, then we want to proceed with the map checking process. Iterate over one of the two mapped strings. Compare each char to the other strings char map, if they are not the same return false. If all checks pass we can now return true.

function anagram(stringA, stringB) {
  const aCharMap = buildCharMap(stringA)
  const bCharMap = buildCharMap(stringB)

  if (Object.keys(aCharMap).length !== Object.keys(bCharMap).length) {
    return false
  }

  for (let char in aCharMap) {
    if (aCharMap[char] !== bCharMap[char]) {
      return false
    }
  }

  return true
}

function buildCharMap(str) {
  const charMap = {}

  for (let char of str.replace(/[^\w]/g, '').toLowerCase()) {
    charMap[char] = charMap[char] + 1 || 1
  }

  return charMap
}