新增一系列数组操作的工具函数 #12

Merged
zhangdeman merged 8 commits from feature/arr_util into master 2025-12-04 10:49:44 +08:00
Showing only changes of commit 98f7414d9e - Show all commits

View File

@ -7,6 +7,8 @@
// Date : 2025-11-25 11:30 // Date : 2025-11-25 11:30
package op_array package op_array
import "fmt"
// ToMap 数组转map // ToMap 数组转map
func ToMap[Key comparable, Value any](dataList []Value, keyFormat func(item Value) Key) map[Key]Value { func ToMap[Key comparable, Value any](dataList []Value, keyFormat func(item Value) Key) map[Key]Value {
res := make(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 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
}