How to remove duplicate values from a slice in Go

Overview

In this shot, we’ll learn how to remove duplicate values from a slice in Go. There is no inbuilt function or method present in Go to remove duplicate values from a slice.

We’ll follow the approach below to achieve this.

Approach

  • Declare an empty new slice and a map.

  • For the given slice with duplicate values, we’ll loop through each element, if it is not already present in the map, then add it to the map as a key and value as true. At the same time, we’ll add the element to a new slice.

  • After traversing the element in the given slice, the new slice will contain elements with no duplicates.

package main
//import packages
import(
"fmt"
)
//program execution starts here
func main(){
//given slice with duplicates
nums_with_dup := []int{11, 12, 15, 13, 11, 15, 25, 21, 29, 12}
//declare an empty map
mp := make(map[int]bool)
//declare an empty slice to store non duplicate values
nums_no_dup := []int{}
//traverse through each element in given slice
for _ , element := range nums_with_dup{
//check if present element present in map
if _ , value := mp[element] ; !value{
//if not present add it
mp[element] = true
//add element to new slice
nums_no_dup = append(nums_no_dup, element)
}
}
//print the slice with no duplicate values
fmt.Println(nums_no_dup)
}

Explanation

  • Line 11: We add a slice, nums_with_dup, with duplicate numbers.
  • Line 14: We declare an empty map, mp, to track for distinct elements.
  • Line 17: We declare an empty slice, nums_no_dup, to store distinct values.
  • Line 21: We use the for loop to traverse through the slice, nums_with_dup.
  • Line 24: We check if the current element is not present in the map, mp. If it is not present, we add it to the map as key and value as true and add the same element to slice, nums_no_dup. Therefore, when we encounter the same element again while we traverse the slice, we don’t add it to the slice. This way, we eliminate duplicate values.
  • Line 34: We print the slice with no duplicate values.

Free Resources