map切片排序

Golang
490
0
0
2022-08-26
标签   Golang基础

map切片根据某个字段值进行排序

思路

  1. 以字段值为 key 创建一个新的map mapData
  2. 以字段值创建一个key的切片 keySplice
  3. 循环切片slice组装新的mapDatakeySplice的切片
  4. keySplice 进行排序
  5. 循环 keySplicemapData中根据key取值
package main

import (
    "fmt" 
    "sort" 
    "strconv"
)

func main() {
    b := []map[string]string{}
    str1 := map[string]string{"name": "zhangsan", "age": "1"}
    str2 := map[string]string{"name": "zhangsan", "age": "111"}
    str3 := map[string]string{"name": "zhangsan", "age": "11"}
    str4 := map[string]string{"name": "zhangsan", "age": "2"}
    str5 := map[string]string{"name": "zhangsan", "age": "22"}
    str6 := map[string]string{"name": "zhangsan", "age": "222"}

    b = append(b, str1, str2, str3, str4, str5, str6)

    // 排序前
    fmt.Println(b)
    fmt.Printf("排序前 ==> %s \n", b)
    // 输出结果 [map[age:1 name:zhangsan] map[age:111 name:zhangsan] map[age:11 name:zhangsan] map[age:2 name:zhangsan] map[age:22 name:zhangsan] map[age:222 name:zhangsan]]
    a, _ := fieldSort(b, "age")

    // 排序后
    fmt.Printf("排序后 ==> %s \n", a)
    // 输出结果 [map[age:1 name:zhangsan] map[age:2 name:zhangsan] map[age:11 name:zhangsan] map[age:22 name:zhangsan] map[age:111 name:zhangsan] map[age:222 name:zhangsan]]
}

func fieldSort(slice []map[string]string, fieldName string) (data []map[string]string, err error) {
    mapData := make(map[int]map[string]string)
    var keySplice []int 
    for _, v := range slice {
        // 字符串转int(根据类型进行转换)
        key, err := strconv.Atoi(v[fieldName])
        if err != nil {
            return nil, err
        }
        mapData[key] = v
        keySplice = append(keySplice, key)
    }

    sort.Ints(keySplice)
    for _, v := range keySplice {
        data = append(data, mapData[v])
    }
    return data, err

}

也可以使用golang的内置方法 sort.Slice

方法 func Slice(x interface{}, less func(i int, j int) bool)

// sortType 为true时 升序 false 降序
func fieldSort(slice []map[string]string, fieldName string, sortType bool) (data []map[string]string) {
    sort.Slice(slice, func(i, j int) bool {
        numi, _ := strconv.Atoi(slice[i][fieldName])

        numj, _ := strconv.Atoi(slice[j][fieldName])

        if sortType {
            return numi < numj
        } else {
            return numi > numj
        }

    })
    return slice

}