Sort 2D array of structs Golang

Issue

I want to create a consistent ordering for a 2D slice of structs, I am creating the 2D slice from a map so the order is always different.

My structs look like

// Hit contains the data for a hit.
type Hit struct {
    Key  string  `json:"key"`
    Data []Field `json:"data"`
}

// Hits stores a list of hits.
type Hits [][]Hit

I want to provide a consistent order for the contents of my Hits type.

I have tried:


func (c Hits) Len() int { return len(c) }


func (c Hits) Swap(i, j int) { c[i], c[j] = c[j], c[i] }


func (c Hits) Less(i, j int) bool { return strings.Compare(c[i][0].Key, c[j][0].Key) == -1 }

But the results still seem to come back in random order.

I was thinking of possibly hashing each item in the slice but thought there might be an easier option

Solution

The order of iteration over a map, because it’s a hash table is rather indeterminate (it’s not, really — insert items with the same keys in the same exact sequence into 2 maps and the order of iteration for each will be identical).

Assuming that your map is a map[string]Hit, to iterate it over in a determinate order, I would enumerate the set of keys in the map, sort that, and use that sorted set to enumerate the map.

Something like this:

package main

import (
  "fmt"
  "sort"
)

type Hit struct {
  Key  string  `json:"key"`
  Data []Field `json:"data"`
}

type Field struct {
  Value string `json:"value"`
}

func main() {
  var mapOfHits = getSomeHits()
  var sortedHits = sortHits(mapOfHits)
  
  for _, h := range sortedHits {
    fmt.Println(h.Key)
  }

}

func getSomeHits() map[string]Hit {
  return make(map[string]Hit, 0)
}

func sortHits(m map[string]Hit) []Hit {
  keys := make([]string, 0, len(m))
  sorted := make([]Hit, 0, len(m))
  
  for k := range m {
    keys = append(keys, k)
  }

  sort.Strings(keys)

  for _, k := range keys {
    sorted = append(sorted, m[k])
  }

  return sorted
}

Answered By – Nicholas Carey

Answer Checked By – Cary Denson (GoLangFix Admin)

Leave a Reply

Your email address will not be published.