Problem:

Implement a function allAnagramGroups() that, given many input strings, will identify and group words that are anagrams of each other.

Given this example input:

[ “pear”,“dirty room”,“amleth”,“reap”,“tinsel”,“tesla”,“hamlet”,“dormitory”,“listen”,“silent”]

The output should be an array-of-arrays.

[ [“pear”,“reap”], [“dirty room”, “dormitory”], [“amleth”,“hamlet”], [“tinsel”,“listen”,“silent”], [“tesla”] ]

Solution:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
function all_anagram_groups(words) {
  var anagrams = [];
  var tmp = [];

  for (var i = 0; i < words.length; i++) {

    if (undefined === words[i]) {
      continue;
    }

    var word = words[i];
    var alphabeticalWord = word.split("").sort().join("").replace(/\s/g,'');

    tmp.push(words[i]);

    for (var j = 0; j < words.length; j++) {

      if (i === j || undefined === words[j]) {
        continue;
      }

      var otherWord = words[j];
      var alphabeticalOtherWord = otherWord.split("").sort().join("").replace(/\s/g,'');

      if (alphabeticalWord === alphabeticalOtherWord) {
        tmp.push(words[j]);
        delete words[words.indexOf(words[j])];
      }
    }
    anagrams.push(tmp);
    tmp = [];
    delete words[words.indexOf(words[i])];
  }
  console.log(anagrams);
};