• 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 (可以,很细心很详细)

    I can see a bigger world.
  • 相关阅读:
    CSS 中 Position relative 和 absolute区别
    感受到LDT的好处
    Map数据结构
    break和continue
    vue的ref属性
    css小样式
    搭建vue开发环境
    setTimeout和clearTimeout
    垂直居中
    vertical-align 属性
  • 原文地址:https://www.cnblogs.com/xuweiqiang/p/15555576.html
Copyright © 2020-2023  润新知