Skip to content

Instantly share code, notes, and snippets.

@tinabme
Created October 25, 2019 20:29
Show Gist options
  • Save tinabme/fe6878f5cff42f60a537262503f9b765 to your computer and use it in GitHub Desktop.
Save tinabme/fe6878f5cff42f60a537262503f9b765 to your computer and use it in GitHub Desktop.
How to find the anagrams

How to find the anagrams

The Request

Given an array of words, write a method to output matching sets of anagrams. Words include "rates, rat, stare, taser, tears, art, tabs, tar, bats, state"

The Code

// our array of words
const words = ['rates', 'rat', 'stare', 'taser', 'tears', 'art', 'tabs', 'tar', 'bats', 'state'];

// main function
function anagramGroups(wordAry){
    // add the groupedWords object that will hold the anagram values organized by the alphabetize word key
    const groupedWords = {};

    // loop over each word in the array

    wordAry.map(word => {
      // alphabetize the word and a separate variable
      alphaWord = word.split('').sort().join('');
      // if the alphabetize word is already a key, push the actual word value (this is an anagram)
      if(groupedWords[alphaWord]) {
        return groupedWords[alphaWord].push(word);
      }
      // otherwise add the alphabetize word key and actual word value (may not turn out to be an anagram)
      groupedWords[alphaWord] = [word]; 
    })
  
    return groupedWords;
}

// store the result (anagrams object) in a variable called collectedAnagrams
const collectedAnagrams = anagramGroups(words);

// iterate over groupedAnagrams, printing out each key:value pair on an individual line
for(const sortedWord in collectedAnagrams) {
  // collectedAnagrams contains more than the original word value then it was an anagram and should be printed.
  if(collectedAnagrams[sortedWord].length > 1) { 
    console.log(collectedAnagrams[sortedWord].toString());
  }
}

The explanation

  • Iterate the array
  • Alphabetize each word
  • Store alphabetize word as the key value in a groupedWords object with the original word as the value
  • Compare alphabetize words to object keys and add additional original words when matches are found
  • Iterate over the return object and output the values, when there is more then one. (single values mean no anagram )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment