Group By in Go

Posted by yhuang
Public (Editable by Users)
Go
Edit
package main

import (
	"fmt"
)

func main() {
	a := []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
	// Here, we know how many paritions we need for grouping by even/odd numbers.
	partitions := make([][]int, 2)
	for _, n := range a {
		idx := n % 2
		partitions[idx] = append(partitions[idx], n)
	}
	fmt.Println(partitions)

	// Next we try grouping by first letter of a word.
	// Here, we use a map to access buckets by a key.
	b := []string{"orange", "apple", "grapefruit", "avocados"}
	partitions2 := map[string][]string{}
	for _, str := range b {
		key := string(str[0])
		partitions2[key] = append(partitions2[key], str)
	}
	fmt.Println(partitions2)
}