diff --git a/docs/slice.md b/docs/slice.md index e1ae41e..fe15428 100644 --- a/docs/slice.md +++ b/docs/slice.md @@ -37,8 +37,9 @@ import ( - [FindLast](#FindLast) - [FlattenDeep](#FlattenDeep) - [ForEach](#ForEach) - + - [GroupBy](#GroupBy) +- [GroupWith](#GroupWith) - [IntSlice](#IntSlice) - [InterfaceSlice](#InterfaceSlice) - [Intersection](#Intersection) @@ -564,6 +565,34 @@ func main() { +### GroupWith +
Return a map composed of keys generated from the results of running each element of slice thru iteratee.
+ +Signature: + +```go +func GroupWith[T any, U comparable](slice []T, iteratee func(T) U) map[U][]T +``` +Example: + +```go +import ( + "fmt" + "github.com/duke-git/lancet/v2/slice" +) + +func main() { + nums := []float64{6.1, 4.2, 6.3} + floor := func(num float64) float64 { + return math.Floor(num) + } + res := slice.GroupWith(nums, floor) + fmt.Println(res) //map[float64][]float64{ 4: {4.2}, 6: {6.1, 6.3},} +} +``` + + + ### IntSliceConvert interface slice to int slice.
diff --git a/docs/slice_zh-CN.md b/docs/slice_zh-CN.md index 2276b2e..b34b2a5 100644 --- a/docs/slice_zh-CN.md +++ b/docs/slice_zh-CN.md @@ -39,6 +39,7 @@ import ( - [ForEach](#ForEach) - [GroupBy](#GroupBy) +- [GroupWith](#GroupWith) - [IntSlice](#IntSlice) - [InterfaceSlice](#InterfaceSlice) - [Intersection](#Intersection) @@ -565,6 +566,32 @@ func main() { +### GroupWith +创建一个map,key是iteratee遍历slice中的每个元素返回的结果。 分组值的顺序是由他们出现在slice中的顺序确定的。每个键对应的值负责生成key的元素组成的数组。iteratee调用1个参数: (value)
+ +函数签名: + +```go +func GroupWith[T any, U comparable](slice []T, iteratee func(T) U) map[U][]T +``` +例子: + +```go +import ( + "fmt" + "github.com/duke-git/lancet/v2/slice" +) + +func main() { + nums := []float64{6.1, 4.2, 6.3} + floor := func(num float64) float64 { + return math.Floor(num) + } + res := slice.GroupWith(nums, floor) + fmt.Println(res) //map[float64][]float64{ 4: {4.2}, 6: {6.1, 6.3},} +} +``` + ### IntSlice将接口切片转换为int切片