Check if two words are anagrams

“Anagrams”, a Black belt challenge from the CurlyScript Dojo. It uses what Grade 10: Array Power Tools: map, filter & reduce teaches, and 4 tests check your answer.

The challenge

Write isAnagram(a, b) that returns true if both texts use exactly the same letters, ignoring case and spaces.

Example
isAnagram("listen", "silent")        // true
isAnagram("Dormitory", "dirty room")  // true

Try it

Write your answer below, then press Check my answer. Your code runs right here in your browser, and the tests tell you what works.

What the tests check

  • isAnagram("listen", "silent") gives true
  • isAnagram("Dormitory", "dirty room") gives true
  • isAnagram("hello", "world") gives false
  • isAnagram("aab", "abb") gives false

Hints

Stuck? Open one hint at a time. Try again after each one.

Hint 1

Make a helper that lowercases, removes spaces, splits into letters, sorts and joins.

Hint 2

Two texts are anagrams if their sorted letters are identical.

A solution

There’s always more than one right way. Read it, make sure you understand it, then try writing it yourself without looking.

Show one possible solution
Solution
function isAnagram(a, b) {
  const key = (s) => s.toLowerCase().replaceAll(" ", "").split("").sort().join("");
  return key(a) === key(b);
}

Learn what you need

This exercise uses what Grade 10: Array Power Tools: map, filter & reduce teaches. Read those notes first if any of it is new.

Practice makes it stick

CurlyScript is a free game that teaches JavaScript from zero: short lessons, an explanation after every answer, and Dojo challenges like this one.

Start learning