js837
js837

Reputation: 133

How do I sort a slice by values of a map

Seems a basic question, but can't find a simple answer.

I have a slice:

[]string{"dog", "cat", "bird"}

What's the best way to sort it by looking up the sorting values in a map:

map[string]int{"dog": 2, "cat":3, "bird": 1}

So that the slice is ordered as below:

[]string{"bird", "dog", "cat"}

Upvotes: 3

Views: 115

Answers (1)

user1804599
user1804599

Reputation:

Implement the sort.Interface interface for a type that stores the data and the weights:

import "sort"

type WeightedStringSlice struct {
    Strings []string
    Weights map[string]int
}

func (s *WeightedStringSlice) Len() int {
    return len(s.Strings)
}

func (s *WeightedStringSlice) Less(i, j int) bool {
    return s.Weights[s.Strings[i]] < s.Weights[s.Strings[j]]
}

func (s *WeightedStringSlice) Swap(i, j int) {
    s.Strings[i], s.Strings[j] = s.Strings[j], s.Strings[i]
}

Then call sort.Sort on it:

data := WeightedStringSlice{
    Strings: []string{"dog", "cat", "bird"},
    Weights: map[string]int{"dog": 2, "cat": 3, "bird": 1},
}
sort.Sort(&data)
fmt.Printf("%v\n", data.Strings)

Live Demo

Upvotes: 5

Related Questions