Skip to content

Commit db2b025

Browse files
committedNov 20, 2023
Add group anagrams
1 parent b7d8364 commit db2b025

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed
 
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
function groupAnagramsWithObject(arr) {
2+
let anagramGroups = {};
3+
for(let str of arr) {
4+
let sortedString = str.split("").sort().join("");
5+
let group = anagramGroups[sortedString];
6+
if(group && group.length > 0) {
7+
anagramGroups[sortedString].push(str);
8+
} else {
9+
anagramGroups[sortedString] = [str];
10+
}
11+
}
12+
return Object.values(anagramGroups);
13+
}
14+
15+
function groupAnagramsWithMap(arr) {
16+
let anagramGroups = new Map();
17+
for(let str of arr) {
18+
let sortedString = str.split("").sort().join("");
19+
if(anagramGroups.has(sortedString)) {
20+
anagramGroups.get(sortedString).push(str);
21+
} else {
22+
anagramGroups.set(sortedString, [str]);
23+
}
24+
}
25+
return Array.from(anagramGroups.values());
26+
}
27+
28+
// Multiple Anagrams
29+
console.log("Input: ['eat', 'tea', 'tan', 'ate', 'nat', 'bat']");
30+
console.log("Output: ", groupAnagramsWithObject(['eat', 'tea', 'tan', 'ate', 'nat', 'bat']));
31+
console.log("---------------");
32+
33+
// Mixed Case Anagrams
34+
console.log("Input: ['Eat', 'Tea', 'Tan', 'Ate', 'Nat', 'Bat']");
35+
console.log("Output: ", groupAnagramsWithObject(['Eat', 'Tea', 'Tan', 'Ate', 'Nat', 'Bat']));
36+
console.log("---------------");
37+
38+
// No Anagrams
39+
console.log("Input: ['apple', 'orange', 'banana']");
40+
console.log("Output: ", groupAnagramsWithMap(['apple', 'orange', 'banana']));
41+
console.log("---------------");

0 commit comments

Comments
 (0)
Please sign in to comment.