Exercise 7: Anagrams

Directions

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

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

Guidelines

Two solutions Use helper function to write DRY code

  1. Convert string to character map and compare
    • Use regular expression (RegExp) \w to remove spaces, puntuactions from a given string
    • String.prototype.replace(), String.prototype.toLowerCase(), String.prototype.length
    • Pull out keys from an object: Object.keys(obj) returns an array
    • Object has no 'length' property
  2. Sort the string and compare
    • Use Array.prototype.sort() method

Solution

In [3]:
function anagrams(stringA, stringB) {
  return cleanString(stringA) === cleanString(stringB);
}

// Helper function
function cleanString(str){
  return str.replace(/[^\w]/g, "").toLowerCase().split("").sort().join(""); // remember join()
}

Alernative Solution

In [2]:
function anagrams(stringA, stringB) {
  let charMapA = makeCharMap(stringA);
  let charMapB = makeCharMap(stringB);

  // Pull out keys from an object
  if (Object.keys(charMapA).length !== Object.keys(charMapB).length){
    return false;
  }

  for (let key in charMapA){
    if (charMapA[key] !== charMapB[key]){
      return false;
    }
  }

  return true;
}

// Helper function
function makeCharMap(str){
  let charMap = {};
  for (let char of str.replace(/[^\w]/g, "").toLowerCase()){
    if (!charMap[char]){
      charMap[char] = 1;
    } else {
      charMap[char]++;
    }
  }
  return charMap;
}
In [4]:
anagrams('rail safety', 'fairy tales')
Out[4]:
true
In [5]:
anagrams('RAIL! SAFETY!', 'fairy tales')
Out[5]:
true
In [6]:
anagrams('Hi there', 'Bye there')
Out[6]:
false