Skip to content
Node: _.groupBy(arr, fn)github.com/sahilkhaire/gox/slice

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][]T

Compare: 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)
}

Back to slice package overview

MIT Licensed · Built for Node.js developers moving to Go