Start learning free

LESSON 232 OF 289 · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

Group Words by First Letter in TypeScript: Object of Arrays

Practice Read the full explanation

Given an array words of lowercase words, group the words by their first letter. Return a dictionary where each key is a first letter, written as a one-character string, and its value is an array of all the words that start with that letter.

Inside each group, keep the words in the order they have in words. The order of the entries in the dictionary doesn't matter.

Example 1:

Input: words = ["apple", "banana", "avocado", "blueberry", "cherry"]
Output: {"a": ["apple", "avocado"], "b": ["banana", "blueberry"], "c": ["cherry"]}
Explanation: "apple" and "avocado" start with "a", "banana" and "blueberry" start with "b", and "cherry" is alone under "c".

Example 2:

Input: words = ["dog", "cat", "deer", "cow", "duck"]
Output: {"d": ["dog", "deer", "duck"], "c": ["cat", "cow"]}
Explanation: "dog" comes before "deer" and "duck" in words, so it comes first in the "d" group too.

Example 3:

Input: words = ["hello"]
Output: {"h": ["hello"]}
Explanation: One word makes one group.

Rules:

  • words has at least one word.
  • Every word has at least one letter and only lowercase letters a-z.
  • A word that appears more than once in words appears as many times in its group.
STEP 1 OF 6
    Ctrl + Enter to check

    TYPESCRIPT · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

    Group Words By First Letter in TypeScript, explained

    Problem overview

    The method groupByFirstLetter receives an array of lowercase words and returns an object. Each key is a first letter, as a one-character string, and its value is the array of all the words that start with that letter. Inside each group the words keep the order they have in words, and a word that appears twice appears twice in its group. The order of the keys doesn't matter.

    For ["apple", "banana", "avocado", "blueberry", "cherry"] the result is {"a": ["apple", "avocado"], "b": ["banana", "blueberry"], "c": ["cherry"]}. For ["dog", "cat", "deer", "cow", "duck"] it is {"d": ["dog", "deer", "duck"], "c": ["cat", "cow"]}. A single word, ["hello"], makes one group: {"h": ["hello"]}.

    Approach

    Each word belongs to exactly one group, so one pass over words is enough. For each word:

    • find its group's key, which is the first letter;
    • if that group doesn't exist yet, create it as an empty array;
    • push the word onto the group.

    Because the words are visited in order and each one goes to the end of its group, every group keeps the order of the input.

    The values here are arrays, not numbers. That changes the "first time" case compared with counting: the new entry starts as an empty array [], and the word is pushed afterwards by code that is shared with the "group already exists" case. So the check comes first and the push comes after it, with no else.

    Step by step

    1. Create the empty object. groups is declared with const and the type { [key: string]: string[] }: string keys, arrays of strings as values.
    2. Loop over the words with for (const word of words).
    3. Get the first letter. const first: string = word[0] is the key of this word's group.
    4. Create the group when it's missing. if (!(first in groups)) sets groups[first] = []. The parentheses matter: ! must turn the whole first in groups check around.
    5. Push the word. groups[first].push(word) runs for every word, after the group is guaranteed to exist.
    6. Return groups after the loop.

    The solution in TypeScript

    class Solution {
        groupByFirstLetter(words: string[]): { [key: string]: string[] } {
            const groups: { [key: string]: string[] } = {};
            for (const word of words) {
                const first: string = word[0];
                if (!(first in groups)) {
                    groups[first] = [];
                }
                groups[first].push(word);
            }
            return groups;
        }
    }
    

    Details worth knowing:

    • word[0] is a string. Indexing a string gives a one-character string, which works as an object key. Every word has at least one letter, so word[0] exists.
    • !(first in groups). Without the parentheses, !first in groups applies ! to first before in runs, which is a different check.
    • Arrays are references. groups[first] is the array stored in the object, not a copy. Pushing onto it changes the array inside groups, so nothing needs to be assigned back.
    • Types are erased. string[] in the index signature is checked by the compiler only. At run time the values are ordinary arrays.

    Edge cases and common mistakes

    • Pushing before the group exists. groups[first] would be undefined, and undefined.push(word) throws a TypeError. The check that creates the group has to come first.
    • Replacing the group every time. Setting groups[first] = [] without the check would empty the group at each word, leaving one word per group.
    • Repeated words. They are kept: ["go", "go", "gum"] gives {"g": ["go", "go", "gum"]}.
    • Sharing one array. Creating a fresh [] for each key avoids groups that accidentally share a list.

    Testing

    • ["apple", "banana", "avocado", "blueberry", "cherry"] gives {"a":["apple","avocado"],"b":["banana","blueberry"],"c":["cherry"]}.
    • ["dog", "cat", "deer", "cow", "duck"] gives {"d":["dog","deer","duck"],"c":["cat","cow"]}.
    • ["hello"] gives {"h":["hello"]}.
    • ["go", "go", "gum"] gives {"g":["go","go","gum"]}.
    Keep going with TypeScript1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free