How to group words by first letter in Go

1 Answer

0 votes
package main

import (
    "fmt"
)

// groupByFirstLetter groups words by their first character.
func groupByFirstLetter(words []string) map[string][]string {
    groups := make(map[string][]string)

    for _, word := range words {
        // Extract the first letter as a string (Go doesn't have char keys like Python)
        first := string(word[0])

        // Append the word to the slice for this letter.
        // If the key doesn't exist yet, Go treats the slice as nil,
        // and append automatically creates a new underlying array.
        groups[first] = append(groups[first], word)
    }

    return groups
}

func main() {
    // List of words to group
    words := []string{
        "Python", "JavaScript", "C", "Java", "C#", "PHP",
        "C++", "Pascal", "SQL", "Rust",
    }

    grouped := groupByFirstLetter(words)

    // Print each group 
    for letter, group := range grouped {
        fmt.Printf("%s: %v\n", letter, group)
    }

    // Print the entire map 
    fmt.Println(grouped)
}



/*
run:

P: [Python PHP Pascal]
J: [JavaScript Java]
C: [C C# C++]
S: [SQL]
R: [Rust]
map[C:[C C# C++] J:[JavaScript Java] P:[Python PHP Pascal] R:[Rust] S:[SQL]]

*/

 



answered Jan 17 by avibootz
...