GroupBy
Overview
GroupBy groups elements by key from fn (lodash groupBy).
If you are coming from Node.js, the closest pattern is _.groupBy(arr, fn).
Signature
go
func GroupBy[T any, K comparable](in []T, fn func(T) K) map[K][]TCompare: Node.js · Standard Go · gox
js
const byRole = _.groupBy(users, u => u.role);go
byRole := make(map[string][]User)
for _, u := range users {
byRole[u.Role] = append(byRole[u.Role], u)
}go
import "github.com/sahilkhaire/gox/slice"
byRole := slice.GroupBy(users, func(u User) string { return u.Role })Example
go
import "github.com/sahilkhaire/gox/slice"
byRole := slice.GroupBy(users, func(u User) string { return u.Role })Tips
Chain Filter, Map, and Reduce for lodash-style pipelines. Results are new slices — inputs are never mutated.
Standard library alternative
Use the standard library directly:
go
byRole := make(map[string][]User)
for _, u := range users {
byRole[u.Role] = append(byRole[u.Role], u)
}