Sort map by value



examples/sort-map-by-value/sort_map_by_value.go
package main

import (
    "fmt"
    "sort"
)

func main() {
    scores := map[string]int{"Alma": 23, "Cecilia": 12, "David": 37, "Berta": 78}
    fmt.Println(len(scores))
    fmt.Println(scores)
    fmt.Println()

    for name, score := range scores {
        fmt.Printf("%-7v %v\n", name, score)
    }
    fmt.Println()

    names := make([]string, 0, len(scores))
    for name := range scores {
        names = append(names, name)
    }
    fmt.Println(names)
    fmt.Println()

    sort.Slice(names, func(i, j int) bool {
        return scores[names[i]] > scores[names[j]]
    })
    fmt.Println(names)
    fmt.Println()

    for _, name := range names {
        fmt.Printf("%-7v %v\n", name, scores[name])
    }
}

examples/sort-map-by-value/sort_map_by_value.out
4
map[Alma:23 Berta:78 Cecilia:12 David:37]

Berta   78
Alma    23
Cecilia 12
David   37

[Alma Cecilia David Berta]

[Berta David Alma Cecilia]

Berta   78
David   37
Alma    23
Cecilia 12