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"
// 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());
}
}
- 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 )