Skip to content

Instantly share code, notes, and snippets.

@martinusso
Created February 7, 2021 14:38
Show Gist options
  • Save martinusso/6e2ac626cd9b07e3fa96206d6eb490d0 to your computer and use it in GitHub Desktop.
Save martinusso/6e2ac626cd9b07e3fa96206d6eb490d0 to your computer and use it in GitHub Desktop.
sort and reverse map by values - golang
// A slice of pairs that implements sort.Interface to sort and reverse by values
type PairList []Pair
func (p PairList) Len() int { return len(p) }
func (p PairList) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
func (p PairList) Less(i, j int) bool { return p[i].Value < p[j].Value }
func sortMapByValues(m map[string]float64) PairList {
p := make(PairList, len(m))
i := 0
for k, v := range m {
p[i] = Pair{k, v}
i++
}
sort.Sort(p)
return p
}
func reverseMapByValues(m map[string]float64) PairList {
p := make(PairList, len(m))
i := 0
for k, v := range m {
p[i] = Pair{k, v}
i++
}
sort.Sort(sort.Reverse(p))
return p
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment