Golang对SliceMap进行排序

一个很简单的func进行排序、还需要进行实现的有time的排序、string类型的,大家可以参考这个改改:

package main

import (
    "fmt"
    "sort"
)

// Int converts `any` to int.
func Int(any interface{}) int {
    if any == nil {
        return 0
    }
    if v, ok := any.(int); ok {
        return v
    }
    return 0
}

func main() {
    source := []map[string]interface{}{
        {"name": "jack", "age": 18},
        {"name": "rose", "age": 25},
        {"name": "snap", "age": 20},
    }
    r := OrderSliceMap(source, "age", "int", OrderTypeDesc)
    fmt.Println(r)
}

// 排序枚举值
type OrderType string

const (
    OrderTypeDesc OrderType = "desc"
    OrderTypeAsc  OrderType = "asc"
)

// OrderSliceMap 对集合数组按照一个key进行排序
func OrderSliceMap(source []map[string]interface{}, childrenIdx string, childrenDataType string, orderType OrderType) (result []map[string]interface{}) {
    switch childrenDataType {
    case "int":
        cc := []*One{}
        for sourceIdx, sourceItem := range source {
            cc = append(cc, &One{
                Idx: sourceIdx,
                Num: Int(sourceItem[childrenIdx]),
            })
        }
        switch orderType {
        case OrderTypeAsc:
            sort.Sort(OneList(cc))
        case OrderTypeDesc:
            sort.Sort(sort.Reverse(OneList(cc)))
        }
        for _, ccItem := range cc {
            result = append(result, source[ccItem.Idx])
        }
    case "time":
    }
    return
}

type One struct {
    Idx int
    Num int
}
type OneList []*One

func (_this OneList) Len() int {
    return len(_this)
}
func (_this OneList) Less(i, j int) bool {
    return _this[i].Num < _this[j].Num
}
func (_this OneList) Swap(i, j int) {
    _this[i], _this[j] = _this[j], _this[i]
}

参考博客:

https://www.jianshu.com/p/c118d2de698e (可以,很细心很详细)

 

上一篇:社区小程序源码-带后台


下一篇:在eclipse中maven构建Web项目,tomcat插件在maven中的运用