Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,923 questions

51,856 answers

573 users

How to convert an array of strings and group all the anagrams into subarrays in JavaScript

1 Answer

0 votes
/**
 * 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' ]
]

*/

 



answered Nov 13, 2025 by avibootz
...