Sort map having dates in ASC order

Hello,

How can I sort a map having date field in ascending order?
Here’s the example of of code on playground which generates map.

Output :

{
  "10": {
    "charges": 110,
    "from_dates": "2009-11-30T23:00:00Z"
  },
  "20": {
    "charges": 120,
    "from_dates": "2009-11-11T23:00:00Z"
  },
  "30": {
    "charges": 130,
    "from_dates": "2009-11-17T23:00:00Z"
  }
}

Expected Output which I am trying to achieve.

{
  "10": {
    "charges": 120,
    "from_dates": "2009-11-11T23:00:00Z"
  },
  "20": {
    "charges": 130,
    "from_dates": "2009-11-17T23:00:00Z"
  },
  "30": {
    "charges": 110,
    "from_dates": "2009-11-30T23:00:00Z"
  }
}

I tried sort.Sort() but it gives an error cannot use from_dates["from_dates"] (value of type map[int]time.Time) as sort.Interface value in argument to sort.Sort: missing method Len
How Can I sort according to dates.?

Hi @ganesh_salunkhe,

This post might have the solution you are looking for.

In a nutshell,

  • read the map keys into a slice
  • sort the slice
  • read the map values using the sorted keys
3 Likes

Since you’re swapping then sorting on the key values, you need something like this: The Go Playground

2 Likes

Thank you

1 Like