[Golang] Remove Duplicates From Slice or Array


Question

How to remove duplicates from slice or array in Go?

Solution

There are many methods to do this [1]. My approach is to create a map [2] type and for each item in the slice/array, check if the item is in the map. If the item is in the map, the it is duplicate. If not in the map, save it in the map. After finished, the map contains no duplicates in the original slice/array.

The following is an example of above approach.

Run Code on Go Playground

package main

import (
      "fmt"
)

func RemoveDuplicatesFromSlice(s []string) []string {
      m := make(map[string]bool)
      for _, item := range s {
              if _, ok := m[item]; ok {
                      // duplicate item
                      fmt.Println(item, "is a duplicate")
              } else {
                      m[item] = true
              }
      }

      var result []string
      for item, _ := range m {
              result = append(result, item)
      }
      return result
}

func main() {
      var testSlice = []string{"Mike", "Matt", "Nancy", "Adam", "Jenny", "Nancy", "Carl"}
      fmt.Println(testSlice)
      resultSlice := RemoveDuplicatesFromSlice(testSlice)
      fmt.Println(resultSlice)
}

Output:

[Mike Matt Nancy Adam Jenny Nancy Carl]
Nancy is a duplicate
[Jenny Carl Mike Matt Nancy Adam]

Tested on: Go Playground

References:

[1]
[2]Go maps in action - The Go Blog