Anagrams finder in javascript

jiaoziren picture jiaoziren · May 26, 2009 · Viewed 65.7k times · Source

I am supposed to write a program in JavaScript to find all the anagrams within a series of words provided. e.g.:

monk, konm, nkom, bbc, cbb, dell, ledl, llde

The output should be categorised into rows:

1. monk konm, nkom;
2. bbc cbb;
3. dell ledl, llde;

I already sorted them into alphabetical order and put them into an array. i.e.:

kmno kmno bbc bbc dell dell

However I am stuck in comparing and finding the matching anagram within the array.

Any help will be greatly appreciated.

Answer

Tim Büthe picture Tim Büthe · May 26, 2009

Here is my take:

var input = "monk, konm, bbc, cbb, dell, ledl";
var words = input.split(", ");

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

  var word = words[i];
  var alphabetical = word.split("").sort().join("");

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

    if (i === j) {
      continue;
    }

    var other = words[j];
    if (alphabetical === other.split("").sort().join("")) {
      console.log(word + " - " + other + " (" + i + ", " + j + ")");
    }
  }
}

where the output would be (the word, the match and the index of both):

monk - konm (0, 1)
konm - monk (1, 0)
bbc - cbb (2, 3)
cbb - bbc (3, 2)
dell - ledl (4, 5)
ledl - dell (5, 4)

To get the characters in the in alphabetical order, I used split("") ot get an array, called sort() and used join("") to get a string from the array.