0
0
GoHow-ToBeginner · 3 min read

How to Sort Map by Value in Go: Simple Example and Tips

In Go, you cannot sort a map directly because maps are unordered. To sort by value, extract the map entries into a slice, then use sort.Slice with a custom comparison function based on the values.
📐

Syntax

To sort a map by value in Go, follow these steps:

  • Create a slice to hold the map's keys or key-value pairs.
  • Use sort.Slice with a comparison function that compares the map values.
  • Access the sorted keys or pairs in order.
go
sort.Slice(slice, func(i, j int) bool {
    return mapVariable[slice[i]] < mapVariable[slice[j]]
})
💻

Example

This example shows how to sort a map of strings to integers by its values in ascending order.

go
package main

import (
	"fmt"
	"sort"
)

func main() {
	m := map[string]int{"apple": 5, "banana": 2, "cherry": 7, "date": 3}

	// Create a slice to hold the keys
	keys := make([]string, 0, len(m))
	for k := range m {
		keys = append(keys, k)
	}

	// Sort keys slice based on the map values
	sort.Slice(keys, func(i, j int) bool {
		return m[keys[i]] < m[keys[j]]
	})

	// Print sorted map by value
	for _, k := range keys {
		fmt.Printf("%s: %d\n", k, m[k])
	}
}
Output
banana: 2 date: 3 apple: 5 cherry: 7
⚠️

Common Pitfalls

Common mistakes when sorting a map by value in Go include:

  • Trying to sort the map directly, which is not possible because Go maps are unordered.
  • Not creating a separate slice for keys or key-value pairs before sorting.
  • Using the wrong comparison function that compares keys instead of values.

Always remember to sort a slice derived from the map, not the map itself.

go
package main

import (
	"fmt"
	"sort"
)

func main() {
	m := map[string]int{"a": 3, "b": 1, "c": 2}

	// Wrong: Trying to sort map directly (this will not compile)
	// sort.Slice(m, func(i, j int) bool {
	// 	return m[i] < m[j]
	// })

	// Right: Create slice of keys and sort by values
	keys := make([]string, 0, len(m))
	for k := range m {
		keys = append(keys, k)
	}

	sort.Slice(keys, func(i, j int) bool {
		return m[keys[i]] < m[keys[j]]
	})

	for _, k := range keys {
		fmt.Println(k, m[k])
	}
}
Output
b 1 c 2 a 3
📊

Quick Reference

Tips for sorting a map by value in Go:

  • Maps are unordered; sorting requires a slice.
  • Extract keys or key-value pairs into a slice.
  • Use sort.Slice with a comparison function on values.
  • Iterate over the sorted slice to access map entries in order.

Key Takeaways

You cannot sort a map directly in Go because maps are unordered.
Extract keys into a slice and sort that slice based on map values using sort.Slice.
Always use a custom comparison function to compare map values during sorting.
Iterate over the sorted slice to access map entries in sorted order.
Avoid trying to sort the map itself; it will cause errors or unexpected behavior.