How to sort slice of slices in Go
The sort package in the Golang standard library is very powerful, it enables you to sort the standard Go types (int, string, etc) super easily.
If you need to sort a slice of slices, you can do so by providing an anonymous function to sort.Slice. In this example we intend to sort the slice by the second unit of each member of the slice (h, a, x).
Let’s remind ourselves that >=, <=, <, > operators can be used to find the lexical order of strings in Go. Like so:
slice := [][]string{
{"2", "h"}, {"3", "a"}, {"1", "x"}
}
sort.Slice(slice, func(i, j int) bool {
return slice[i][1] < slice[j][1]
})
fmt.Printf("%v\n", slice)
» go run main.go
[[3 a] [2 h] [1 x]]
Voilà. If you are working with your own types, you can also take advantage of the sort package by making sure that your type implements this interface.