Group Anagrams in TypeScript

function groupAnagrams(strs: string[]): string[][] {
  // Create a map to hold the groups of anagrams
  const map: { [key: string]: string[] } = {};

  // Iterate over each string in the input array
  strs.forEach(str => {
    // Sort the characters of the string to find the anagram key
    const sorted = str.split('').sort().join('');

    // If the key exists in the map, push the current string to its array
    // Otherwise, create a new array with the current string
    if (map[sorted]) {
      map[sorted].push(str);
    } else {
      map[sorted] = [str];
    }
  });

  // Return the values of the map, which are arrays of grouped anagrams
  return Object.values(map);
}

PrevNext