GroupBy function for arrays/slices in Go
How to write a functional GroupBy function in Go using generics, including a unit test. Returns a map with slices.
GroupBy applies a function to each element in the input slice and groups the elements by the function’s return value, returning a map from return values to slices of elements. The function f takes an element of type A and returns a key of type K.
func GroupBy[A any, K comparable](input []A, f func(A) K) map[K][]A {
result := make(map[K][]A)
for _, v := range input {
key := f(v)
result[key] = append(result[key], v)
}
return result
}
func TestGroupBy(t *testing.T) {
input := []string{"apple", "banana", "cherry", "date", "elderberry"}
f := func(a string) int {
return len(a)
}
expected := map[int][]string{5: {"apple"}, 6: {"banana", "cherry"}, 4: {"date"}, 10: {"elderberry"}}
result := util.GroupBy(input, f)
if !reflect.DeepEqual(expected, result) {
t.Errorf("Expected %v, got %v", expected, result)
}
}
Linked Technologies
What it's made of
Go
Fast, simple, and efficient. Ideal for solopreneurs, Go's straightforward syntax and powerful performance allow for quick development and deployment.
Linked Categories
Where it's useful
Data Engineering
Explore the essentials of Data Engineering, delving into how data systems are built and maintained. From organizing data flows to automating complex data processes, discover the tools and techniques that make data easily accessible and useful for everyday projects and insights.