BigDataLearner
BigDataLearner

Reputation: 1468

sort a map of structs in golang

I have a map which is like this

Key: 9970DLXEVOQ0O Value: [{9972IOFNIDER6 0.3},{9972MFYWYJIEK 0.2},{9972QIUUINW6R 0.5}]
Key: 9970DLXEVOQ01 Value: [{9972IOFNIDER6 0.3}]
Key: 9970QYPOYUUIO Value: [{9972VOFA3OJLK 0.4}]

in golang named product_deal in which key is string and value is a struct :

type product_detail struct {
     deal_id string
     rating float64
}

I need to sort the values based on ratings(descending ) in each value field the output should be i.e

Key: 9970DLXEVOQ0O Value: [{9972QIUUINW6R 0.5},{9972IOFNIDER6 0.3},{9972MFYWYJIEK 0.2}]
Key: 9970DLXEVOQ01 Value: [{9972IOFNIDER6 0.3}]
Key: 9970QYPOYUUIO Value: [{9972VOFA3OJLK 0.4}]

Any ideas of how this needs to be done. i did have a look at other post which sort maps but could not get the implementation. Any help would be appreciated.

Upvotes: 0

Views: 4265

Answers (1)

jimt
jimt

Reputation: 26447

To expand on my comment on the original question, here is a working example which can be run on the Go playground. Note that I may have misinterpreted the structure of the types you want to have, but the idea should be clear.

package main

import "fmt"
import "sort"

type Product struct {
    Id     string
    Rating float64
}

type Deal struct {
    Id       string
    products []Product
}

type Deals []Deal

// Ensure it satisfies sort.Interface
func (d Deals) Len() int           { return len(d) }
func (d Deals) Less(i, j int) bool { return d[i].Id < d[j].Id }
func (d Deals) Swap(i, j int)      { d[i], d[j] = d[j], d[i] }

func main() {
    deals := Deals{
        {"9970DLXEVOQ0O", []Product{{"9972MFYWYJIEK", 0.2}}},
        {"9970DLXEVOQ01", []Product{{"9972IOFNIDER6", 0.3}}},
        {"9970QYPOYUUIO", []Product{{"9972VOFA3OJLK", 0.4}}},
        {"9970DLYKLAO8O", []Product{{"9972IOFNIDER6", 0.3}}},
        {"9970QYPMNAUUI", []Product{{"9972QIUUINW6R", 0.5}}},
    }

    sort.Sort(deals)

    for _, d := range deals {
        fmt.Println(d)
    }
}

Upvotes: 12

Related Questions