How to group words by first letter in TypeScript

1 Answer

0 votes
/**
 * Groups an array of words by their first letter.
 *
 * @param words - The list of words to group
 * @returns A dictionary where each key is a letter and each value is an array of words
 */
function groupByFirstLetter(words: string[]): Record<string, string[]> {
  const groups: Record<string, string[]> = {}; // Typed dictionary

  for (const word of words) {
    const firstLetter = word[0]; // Extract first letter

    // If the key doesn't exist yet, create an empty array
    if (!groups[firstLetter]) {
      groups[firstLetter] = [];
    }

    // Add the word to its group
    groups[firstLetter].push(word);
  }

  return groups;
}

// List of words to group
const words: string[] = [
  "Python", "JavaScript", "C", "Java", "C#", "PHP",
  "C++", "Pascal", "SQL", "Rust"
];

const groupedWords: Record<string, string[]> = groupByFirstLetter(words);

// Print each group 
for (const letter in groupedWords) {
  console.log(`${letter}: [${groupedWords[letter].join(", ")}]`);
}

// Print the entire dictionary 
console.log(groupedWords);

 
 
/*
run:
 
"P: [Python, PHP, Pascal]" 
"J: [JavaScript, Java]" 
"C: [C, C#, C++]" 
"S: [SQL]" 
"R: [Rust]" 
{
  "P": [
    "Python",
    "PHP",
    "Pascal"
  ],
  "J": [
    "JavaScript",
    "Java"
  ],
  "C": [
    "C",
    "C#",
    "C++"
  ],
  "S": [
    "SQL"
  ],
  "R": [
    "Rust"
  ]
} 
 
*/

 



answered Jan 16 by avibootz
...