gitee.com/zhongguo168a/gocodes@v0.0.0-20230609140523-e1828349603f/datax/listx/group.go (about)

     1  package listx
     2  
     3  import "math"
     4  
     5  // GroupByCount 按指定数量分组
     6  func (list *List) GroupByCount(count int) (r []*List) {
     7  	groupLen := int(math.Ceil(float64(list.Length()) / 8))
     8  	for i := 0; i < groupLen; i++ {
     9  		a := &List{}
    10  		start := i * count
    11  		end := int(math.Min(float64(start+count), float64(list.Length())))
    12  		for j := start; j < end; j++ {
    13  			a.Push(list.At(j))
    14  		}
    15  
    16  		r = append(r, a)
    17  	}
    18  	return
    19  }
    20  
    21  func (list *List) GroupByCustomKey(getKey func(item interface{}) string) map[string]*List {
    22  	r := map[string]*List{}
    23  	for _, val := range list.Slice() {
    24  		key := getKey(val)
    25  		a, has := r[key]
    26  		if !has {
    27  			a = &List{}
    28  			r[key] = a
    29  		}
    30  		a.Push(val)
    31  	}
    32  
    33  	return r
    34  }