Golang : Delete duplicate items from a slice/array
Problem :
Fairly common question or task that a programmer will face from time to time. How to remove duplicate items in a slice ?
For example, this slice has 2 string duplicates :
duplicate := []string{"Hello", "World", "GoodBye", "World", "We", "Love", "Love", "You"}
Solution :
Iterate over the slice and copy over the non duplicate items to a new slice.
package main
import (
"fmt"
)
func printslice(slice []string) {
fmt.Println("slice = ", slice)
//for i := range slice {
// fmt.Println(i, slice[i])
//}
}
func stringInSlice(str string, list []string) bool {
for _, v := range list {
if v == str {
return true
}
}
return false
}
func main() {
duplicate := []string{"Hello", "World", "GoodBye", "World", "We", "Love", "Love", "You"}
printslice(duplicate)
//need to delete duplicate data from slice
// the idea is to copy data over to a new slice without the duplicate
cleaned := []string{}
for _, value := range duplicate {
if !stringInSlice(value, cleaned) {
cleaned = append(cleaned, value)
}
}
printslice(cleaned)
}
Output :
slice = [Hello World GoodBye World We Love Love You]
slice = [Hello World GoodBye We Love You]
NOTE : I'm sure there are more efficient solution out there. But for simple task with small set of data. This solution should be sufficient.
See also : Golang : automatically figure out array length(size) with three dots
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+18.9k Golang : Populate dropdown with html/template example
+19.7k Golang : Determine if directory is empty with os.File.Readdir() function
+6k Golang : Process non-XML/JSON formatted ASCII text file example
+12.4k Golang : Pass database connection to function called from another package and HTTP Handler
+14.4k Golang : Get URI segments by number and assign as variable example
+13.4k Golang : Query string with space symbol %20 in between
+28.1k Golang : Read, Write(Create) and Delete Cookie example
+5.1k Javascript : Change page title to get viewer attention
+13.9k Golang : Simple word wrap or line breaking example
+12.8k Golang : Skip blank/empty lines in CSV file and trim whitespaces example
+14.2k Golang : GUI with Qt and OpenCV to capture image from camera
+30.1k Golang : How to redirect to new page with net/http?