map切片根据某个字段值进行排序
思路
- 以字段值为
key
创建一个新的mapmapData
- 以字段值创建一个
key
的切片keySplice
- 循环切片
slice
组装新的mapData
和keySplice
的切片 - 把
keySplice
进行排序 - 循环
keySplice
从mapData
中根据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
}