R
E
A
C
T
O

xamples
epeat
ode
pproach
ptimize
est
{Anagram Detection}

Problem
An anagram is a word, phrase or name formed by rearranging the letters of another, such as cinema, formed from iceman.
var words = ["cat", "act", "ignore", "a phrase", "tape", "pate", "e hpsara"];
console.log(anagramFunction(words));
//output should be
1. cat, act
2. a phrase, e hpsara
3. tape, pate
1. You are given an array of strings only (could be words, phrases etc).
2. Create a function to find all the anagrams within that array.
3. The output should be an ordered list - each row displaying a word and all of its anagrams.
4. Your function output should ignore all words that are not anagrams.
Approach
1. Take all the words in the array and using the map function, split each word, sort them and join them again.
["cat", "act", "ignore", "a phrase", "tape", "pate", "e hpsara"]
[ 'act', 'act', 'eginor', ' aaehprs', 'aept', 'aept', ' aaehprs' ]
2. Create a hash table of the words
{ act: [ 'cat', 'act' ],
eginor: [ 'ignore' ],
' aaehprs': [ 'a phrase', 'e hpsara' ],
aept: [ 'tape', 'pate' ] }
3. Go through the table and if the array length of each word is > 1, its anagram exists. Return the words.
1. cat, act
2. a phrase, e hpsara
3. tape, pate

Solution
var table = {};
function anagramFunction(words) {
//Map, split, sort and join all the words in the array
var sortedWords = words.map( function( word ){
return word.split('').sort().join('');
});
/* Create a table of key/value pairs. The key would be the first instance
of each sorted word and value should be an array that consists of the word
and its anagrams (or just the word itself if there is no anagram) */
sortedWords.forEach( function ( sortedWord, index){
table[sortedWord] = table[sortedWord] || [];
table[sortedWord].push( words[index] );
});
//All arrays in the table with a size > 1 are anagrams. Return those words in an ordered list.
Object.keys( table ).forEach( function( sortedWord , index ){
var value = table[sortedWord];
if( value.length > 1 ){
console.log( index + 1 + ". " + value.join(', ') );
}
});
}

Conclusion
- The Object.keys() method returns an array of a given object's own enumerable properties, in the same order as that provided by a for...in loop (the difference being that a for-in loop enumerates properties in the prototype chain as well).
Anagram Detection
By lindakung417
Anagram Detection
Detect anagrams in an array
- 1,537