mirror of
https://github.com/rjNemo/underscore
synced 2026-06-06 10:36:43 +00:00
15 lines
352 B
Go
15 lines
352 B
Go
package underscore
|
|
|
|
// GroupBy splits a slice into a map[K][]V grouped by the result of the iterator function.
|
|
func GroupBy[K comparable, V any](values []V, f func(V) K) map[K][]V {
|
|
res := make(map[K][]V, 0)
|
|
for _, v := range values {
|
|
k := f(v)
|
|
if r, ok := res[k]; ok {
|
|
res[k] = append(r, v)
|
|
} else {
|
|
res[k] = []V{v}
|
|
}
|
|
}
|
|
return res
|
|
}
|