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

Merged
zhangdeman merged 8 commits from feature/arr_util into master 2025-12-04 10:49:44 +08:00
98f7414d9e feat: 增加数组分组能力
白茶清欢
2025-11-26 21:00:36 +08:00
Commit 5 of 8
Show all commits
+21
View File
@@ -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
}
Reference in new issue
Block a user
Blocking a user prevents them from interacting with repositories, such as opening or commenting on pull requests or issues. Learn more about blocking a user.