Skip to content

Commit 2987182

Browse files
committed
ArrayKeyFuncBy like group by
1 parent dfeb3df commit 2987182

File tree

2 files changed

+22
-0
lines changed

2 files changed

+22
-0
lines changed

example/example.go

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ package main
33
import (
44
"fmt"
55
lib "github.com/maxiloEmmmm/go-tool"
6+
"strings"
67
)
78

89
func main() {
@@ -17,8 +18,13 @@ func main() {
1718
{Name: "hxm2", Age: 12},
1819
{Name: "hxm3", Age: 13},
1920
{Name: "hxm4", Age: 15},
21+
{Name: "gxm", Age: 12},
2022
}
2123

24+
fmt.Println(lib.ArrayKeyFuncBy(&test, "Name", func(d interface{}) interface{} {
25+
return lib.AssetsReturn(strings.HasPrefix(d.(string), "hx"), "hx", "gx")
26+
}))
27+
2228
fmt.Println(lib.ArrayFirst(&test))
2329
fmt.Println(lib.InArray([]string{"!", "#"}, "#"))
2430

tool.go

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -241,6 +241,22 @@ func ArrayKeyBy(data interface{}, key string) ArrayKeyByS {
241241
return dst
242242
}
243243

244+
func ArrayKeyFuncBy(data interface{}, key string, cb func(interface{}) interface{}) ArrayKeyByS {
245+
v := TryInterfacePtr(data)
246+
AssetsSlice(v.Kind(), "数组转换接口错误, 非数组接口")
247+
248+
vl := v.Len()
249+
dst := make(ArrayKeyByS, vl)
250+
for i := 0; i < vl; i++ {
251+
tmp := v.Index(i).Interface()
252+
// 相信宝贝你不会存在不存在的情况 - -
253+
k, _ := Get(tmp, key)
254+
kt := cb(k)
255+
dst[kt] = append(dst[kt], tmp)
256+
}
257+
return dst
258+
}
259+
244260
func ArrayKeyByFunc(data interface{}, key string, cb func(interface{}, interface{}) interface{}) map[interface{}]interface{} {
245261
v := TryInterfacePtr(data)
246262
AssetsSlice(v.Kind(), "数组转换接口错误, 非数组接口")

0 commit comments

Comments
 (0)