diff --git a/op_array/util.go b/op_array/util.go index 9efa97e..118abd1 100644 --- a/op_array/util.go +++ b/op_array/util.go @@ -7,6 +7,8 @@ // Date : 2025-11-25 11:30 package op_array +import "fmt" + // ToMap 数组转map func ToMap[Key comparable, Value any](dataList []Value, keyFormat func(item Value) Key) map[Key]Value { res := make(map[Key]Value) @@ -47,3 +49,22 @@ func Filter[Value any](dataList []Value, filterValue func(item Value) bool) []Va } return res } + +// Group 按照指定字段进行分组 +func Group[Key comparable, Value any](dataList []Value, keyFormat func(item Value) Key) [][]Value { + keyList := make([]string, 0) + dataTable := make(map[string][]Value) + res := make([][]Value, 0) + for _, item := range dataList { + key := fmt.Sprintf("%v", keyFormat(item)) + if _, ok := dataTable[key]; !ok { + keyList = append(keyList, key) + } + dataTable[key] = append(dataTable[key], item) + } + formatList := make([][]Value, 0) + for _, key := range keyList { + formatList = append(formatList, dataTable[key]) + } + return res +}