Group By

Partitions the list into groups.

Examples Filter
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)
}
Last Run  :
[[0 2 4 6 8] [1 3 5 7 9]]
map[a:[apple avocados] g:[grapefruit] o:[orange]]