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.
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)}
nums_with_dup
, with duplicate numbers.mp
, to track for distinct elements.nums_no_dup
, to store distinct values.for
loop to traverse through the slice, nums_with_dup
.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.