Sort Map by Value Image Sort Map by Value

In this code snippet, we are going to look at how you can quickly and easily sort maps in Go using the sort package.

Sort Map by Length of Keys

main.go
package main

import (
	"fmt"
	"sort"
)

func main() {
	mymap := map[string]int{"Elliot": 25, "Sophie": 24, "Fraser": 20}

	// make an array of type string to store our keys 
	keys := []string{}

	// iterate over the map and append all keys to our
	// string array of keys
	for key := range mymap {
		keys = append(keys, key)
	}

	// use the sort method to sort our keys array
	sort.Strings(keys)

	for _, key := range keys {
		fmt.Println(key, mymap[key])
	}
}

When we run this, we should see that we are able to retrieve the values from our map in order of the length of the string key.

$ go run main.go
Elliot 25
Fraser 20
Sophie 24

Further Reading

If you enjoyed this code snippet, you may also enjoy these articles:

Elliot Forbes

Elliot Forbes
Twitter: @Elliot_f

Hey, I'm Elliot and I've been working on TutorialEdge for the last 4 years! If my work has helped you in any way, shape, or form then please consider supporting my work.

become a patron Buy Me A Coffee