Start learning free

LESSON 229 OF 671 · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

Group Words by First Letter in JavaScript: An 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

    JAVASCRIPT · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

    Group Words By First Letter in JavaScript, explained

    Problem overview

    The method groupByFirstLetter(words) receives an array of lowercase words. It returns an object where each key is a first letter and each value is an array of all the words that start with that letter, in the order they appear in words.

    For ["dog", "cat", "deer", "cow", "duck"] the result is {"d": ["dog", "deer", "duck"], "c": ["cat", "cow"]}. "dog" comes before "deer" and "duck" in the input, so it also comes first in the "d" group.

    Approach

    This is a dictionary of lists. Each word belongs to exactly one group, chosen by its first letter, so a single pass is enough. For each word, find its group; if the group doesn't exist yet, create it as an empty array; then add the word to it.

    The creation step is separate from the adding step. Creating the group only when it's missing means the first word of a letter starts the group, and later words of that letter find it already there. The add step then runs for every word, whether the group is new or not.

    Step by step

    1. Create an empty object named groups with const.
    2. Loop over the words with for (const word of words).
    3. Take the first letter with const first = word[0]. It is the key of this word's group.
    4. Create the group if it is missing. The check is !(first in groups), and the body sets groups[first] = [].
    5. Push the word onto groups[first].
    6. Return groups after the loop.

    The solution in JavaScript

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

    The details to notice:

    • Indexing a string. word[0] is a one-character string, such as "d". That is the key type the lesson asks for.
    • The parentheses in !(first in groups). Without them, !first in groups would apply ! to first before the in check, and then check whether a key named "false" exists. The parentheses make ! negate the whole check.
    • Arrays are shared by reference. groups[first] is the array stored in the object, not a copy. Calling push on it changes the array inside groups, so no assignment back is needed.
    • const inside the loop. word and first are fresh on every pass, so const is fine.

    Tracing the example

    For ["dog", "cat", "deer", "cow", "duck"]: "dog" has no "d" group yet, so one is created and "dog" is added. "cat" creates "c". "deer" finds the "d" group and joins it, then "cow" joins "c", and "duck" joins "d". The final object is {d: ["dog", "deer", "duck"], c: ["cat", "cow"]}. The groups keep the words in input order because the loop meets them in that order and push adds at the end.

    Edge cases and common mistakes

    • Replacing the group every time. If the line groups[first] = [] is not inside the if, every word wipes its group, and each ends up with only its last word.
    • Pushing before the group exists. groups[first] would be undefined, and calling push on it throws a TypeError.
    • Repeated words. They are kept. ["go", "gone", "go"] gives {g: ["go", "gone", "go"]}.
    • One word. ["hello"] gives {h: ["hello"]}.
    • Empty strings. The lesson guarantees at least one letter. For an empty word, word[0] is undefined, which would become a key named "undefined".

    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", "gone", "go"] gives {g: ["go", "gone", "go"]}.
    Keep going with JavaScript650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free