Sort map by values

Hello,
I have a country hash map where the keys are the respective iso-3166 alpha-2 codes and values are the common names of the countries. When trying to iterate through the hashmap Hugo sorts by the keys. How do I sort by value on a map?

Example code:

---
au: Australia
ch: Switzerland
gb: United Kingdom
kr: South Korea
---
{{ range $id, $name := .Site.Data.countries }}
  <a href="{{ $id }}">{{ $name }}</>
{{ end }}

Desired result:

  • Australia
  • South Korea
  • Switzerland
  • United Kingdom

Current result:

  • Australia
  • Switzerland
  • United Kingdom
  • South Korea

Use the value keyword. Examples:

{{ range $id, $name := sort .Site.Data.countries "value" }} <-- default sort is ascending
{{ range $id, $name := sort .Site.Data.countries "value" "asc" }}  
{{ range $id, $name := sort .Site.Data.countries "value" "desc" }}
1 Like

Hmm that sorts the countries by name but now $id represents the loop iteration and not the hash key

Sorry about that. I was looking at values only.

Sometimes it’s easier to visualize the data as JSON (the jsonify function can help with this). Your data is currently a single object with four keys. It is not an array.

{
  "au": "Australia",
  "ch": "Switzerland",
  "gb": "United Kingdom",
  "kr": "South Korea"
}

In this case, the sort function discards the keys, leaving you with an array

[
  "Australia",
  "South Korea",
  "Switzerland",
  "United Kingdom"
]

I suggest you restructure your data as an array of objects:

- id: au
  name: Australia
- id: ch
  name: Switzerland
- id: gb
  name: United Kingdom
- id: kr
  name: South Korea

In JSON that looks like:

[
  {
    "id": "au",
    "name": "Australia"
  },
  {
    "id": "ch",
    "name": "Switzerland"
  },
  {
    "id": "gb",
    "name": "United Kingdom"
  },
  {
    "id": "kr",
    "name": "South Korea"
  }
]

Then you can do:

{{ range sort .Site.Data.countries2 "name" }}
  <a href="{{ .id }}">{{ .name }}</a>
{{ end }}
1 Like

That worked!
Funnily enough that’s actually how the YAML file looked initially today :upside_down_face:

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.