Monday, May 13, 2024
 Popular · Latest · Hot · Upcoming
108
rated 0 times [  109] [ 1]  / answers: 1 / hits: 116097  / 15 Years ago, tue, may 26, 2009, 12:00:00

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.


More From » string

 Answers
18

Javascript objects are excellent for this purpose, since they are essentially key/value stores:



// Words to match
var words = [dell, ledl, abc, cba];

// The output object
var anagrams = {};

for (var i in words) {
var word = words[i];

// sort the word like you've already described
var sorted = sortWord(word);

// If the key already exists, we just push
// the new word on the the array
if (anagrams[sorted] != null) {
anagrams[sorted].push(word);
}
// Otherwise we create an array with the word
// and insert it into the object
else {
anagrams[sorted] = [ word ];
}
}

// Output result
for (var sorted in anagrams) {
var words = anagrams[sorted];
var sep = ,;
var out = ;
for (var n in words) {
out += sep + words[n];
sep = ;
}
document.writeln(sorted + : + out + <br />);
}

[#99456] Thursday, May 21, 2009, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jailynbethanies

Total Points: 686
Total Questions: 119
Total Answers: 99

Location: Cook Islands
Member since Thu, May 21, 2020
4 Years ago
jailynbethanies questions
Wed, Jul 7, 21, 00:00, 3 Years ago
Tue, Jun 22, 21, 00:00, 3 Years ago
Tue, Apr 23, 19, 00:00, 5 Years ago
;