Fork me on GitHub

Groups elements from a source based on a key selection function.

func GroupBy[T any](keySelector KeySelector[T], source any, dest any) *Builder[T]
  • Description: Groups elements from source based on the key returned by keySelector and stores them in dest.
  • Parameters:
    • keySelector: Function that extracts a key from each element of type T. It takes an element of type T and returns a key of type any.
    • source: Source data to group (expects pointers to slices or maps). dest: Destination where grouped elements will be stored (expects pointers to maps).

Example

 1package main
 2
 3import (
 4	"fmt"
 5
 6	collection "github.com/jose78/go-collection/v2"
 7)
 8
 9type Person struct {
10	Name string
11	Age  int
12}
13
14func keySelectorByAge(person Person) any {
15	return person.Age
16}
17
18func main() {
19	people := []Person{
20		{"Alice", 25},
21		{"Bob", 30},
22		{"Charlie", 25},
23	}
24
25	groups := make(map[int][]Person)
26
27	builderError := collection.GroupBy(keySelectorByAge, people, groups)
28
29	if builderError != nil {
30		fmt.Printf("Error during grouping: %v\n", builderError.Error())
31	} else {
32		for age, group := range groups {
33			fmt.Printf("People with age %d:\n", age)
34			for _, person := range group {
35				fmt.Printf("- %s\n", person.Name)
36			}
37		}
38	}
39
40}