Skip to content

Instantly share code, notes, and snippets.



Last active Nov 15, 2017
What would you like to do?
No `sort()` anagram tester
// Takes two strings.
// Returns true if they're anagrams, false if not.
function isAnagram (a, b) {
const remove = (string, pattern) => string.replace(new RegExp(pattern, 'ig'), '');
// Discard whitespace; anagrams can be different numbers of words
let lettersA = remove(a, '\\s');
let lettersB = remove(b, '\\s');
while (lettersA.length && lettersA.length === lettersB.length) {
const letter = lettersA[0];
lettersA = remove(lettersA, letter);
lettersB = remove(lettersB, letter);
return lettersA === lettersB;

This comment has been minimized.

Copy link
Owner Author

@robwierzbowski robwierzbowski commented Nov 14, 2017

Fun coding exercise suggested by Lara Schenck on Twitter:

How my solution works:

  1. Remove all whitespace. Anagrams can be different numbers of words.
  2. Loop!
    1. If either string is empty or they're not equal length, exit the while loop.
    2. Remove all instances of the first letter in lettersA from both strings. Repeat the loop.
  3. Compare strings. If the words are anagrams, both will be '', an empty string.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment