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 packagesimport("fmt")//program execution starts herefunc main(){//given slice with duplicatesnums_with_dup := []int{11, 12, 15, 13, 11, 15, 25, 21, 29, 12}//declare an empty mapmp := make(map[int]bool)//declare an empty slice to store non duplicate valuesnums_no_dup := []int{}//traverse through each element in given slicefor _ , element := range nums_with_dup{//check if present element present in mapif _ , value := mp[element] ; !value{//if not present add itmp[element] = true//add element to new slicenums_no_dup = append(nums_no_dup, element)}}//print the slice with no duplicate valuesfmt.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
forloop 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 astrueand 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.