How to have unique elements in integer array within a map?

Issue

I have a map of string and int array as shown below which is being populated –

  var customerCatalog = make(map[string][]int64)
  for ... {
        var data = "....."
        for _, catalogId := range data.Catalogs {
            var ok bool
            var keys []int64
            var tmp interface{}
            cusId := strconv.FormatInt(int64(catalogId), 10)
            if tmp, ok = customerCatalog[cusId]; !ok {
                keys = []int64{}
            } else {
                keys = tmp.([]int64)
            }
            keys = append(keys, data.ProductId)
            customerCatalog[cusId] = keys
        }
    }

Here data.Catalogs is int32 array. And data.ProductId is int64. So I need to loop over data.Catalogs array and populate my customerCatalog map with unique array values for each data.ProductId key.

As you can see I have value of map as integer array which can have duplicate values in it. I want to make sure integer array for particular key in the map should have unique values in them. Since go doesn’t support generics so that is why we don’t have set so how should we handle this case here?

Solution

Since go doesn’t support generics so that is why we don’t have set

Sets are often implemented using the keys of a hash table; ignore the values.

In Go, use a map[int64]bool.

// Check if an array contains only unique values.
func is_unique(array []int64) bool {
  var unique = map[int64]bool{}

  for _,v := range(array) {
    if unique[v] {
      return false
    }
    unique[v] = true
  }

  return true
}

// Return a deduplicated array
func uniq(array []int64) []int64 {
  var unique = map[int64]bool{}
  keys := make([]int64, 1)

  for _,v := range(array) {
    if _, ok := unique[v]; !ok {
      keys = append(keys, v)
      unique[v] = true
    }
  }

  return keys
}

Answered By – Schwern

Answer Checked By – Marilyn (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.