feat: 增加数组分组能力
This commit is contained in:
@ -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
|
||||||
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user