From 98f7414d9e49d08ca488e928f7b60460d317f1cf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=99=BD=E8=8C=B6=E6=B8=85=E6=AC=A2?= Date: Wed, 26 Nov 2025 21:00:36 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E5=A2=9E=E5=8A=A0=E6=95=B0=E7=BB=84?= =?UTF-8?q?=E5=88=86=E7=BB=84=E8=83=BD=E5=8A=9B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- op_array/util.go | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) 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 +}