How do I sort a custom array of struct using GoLang.
My Code is :
package main
import "fmt"
type TicketDistribution struct {
Label string
TicketVolume int64
}
type TicketDistributionResponse struct {
LevelDistribution []*TicketDistribution
}
func main() {
var response TicketDistributionResponse
response.LevelDistribution = append(response.LevelDistribution, &TicketDistribution{Label: "John", TicketVolume: 3})
response.LevelDistribution = append(response.LevelDistribution, &TicketDistribution{Label: "Bill", TicketVolume: 7})
response.LevelDistribution = append(response.LevelDistribution, &TicketDistribution{Label: "Sam", TicketVolume: 4})
for _, val := range response.LevelDistribution {
fmt.Println(*val)
}
}
This prints the output as
{John 3}
{Bill 7}
{Sam 4}
I want to sort the response object by TicketVolume value in descending order.
After the sort the response object should look like :
{Bill 7}
{Sam 4}
{John 3}
You can use sort.Slice for that. It takes your slice and a sort function.
The sort function itself takes two indices and returns true if the left item is smaller than the right one.
This way you can sort by your own custom criteria.
package main
import (
"fmt"
"sort"
)
type TicketDistribution struct {
Label string
TicketVolume int64
}
type TicketDistributionResponse struct {
LevelDistribution []*TicketDistribution
}
func main() {
var response TicketDistributionResponse
response.LevelDistribution = append(response.LevelDistribution, &TicketDistribution{Label: "John", TicketVolume: 3})
response.LevelDistribution = append(response.LevelDistribution, &TicketDistribution{Label: "Bill", TicketVolume: 7})
response.LevelDistribution = append(response.LevelDistribution, &TicketDistribution{Label: "Sam", TicketVolume: 4})
sort.Slice(response.LevelDistribution, func(i, j int) bool {
a := response.LevelDistribution[i]
b := response.LevelDistribution[j]
return a.TicketVolume > b.TicketVolume
})
for _, val := range response.LevelDistribution {
fmt.Println(*val)
}
}
The use of > in the comparison function sorts the slice descendingly, for ascending order you would use <.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With