/**
* Groups an array of strings into subarrays of anagrams.
*/
function groupAnagrams(words) {
if (!Array.isArray(words)) {
throw new TypeError("Input must be an array of strings.");
}
const map = new Map();
for (const word of words) {
if (typeof word !== "string") {
throw new TypeError("All elements in the array must be strings.");
}
// Sort characters
const sortword = word.split("").sort().join("");
// Group words by their sorted key
if (!map.has(sortword)) {
map.set(sortword, []);
}
map.get(sortword).push(word);
}
// Return grouped anagrams as an array of arrays
return Array.from(map.values());
}
try {
const arr = ["eat", "tea", "rop", "ate", "nat", "orp", "tan", "bat", "pro"];
const result = groupAnagrams(arr);
console.log(result);
} catch (error) {
console.error(error.message);
}
/*
run:
[
[ 'eat', 'tea', 'ate' ],
[ 'rop', 'orp', 'pro' ],
[ 'nat', 'tan' ],
[ 'bat' ]
]
*/