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
+11.7k Golang : Format numbers to nearest thousands such as kilos millions billions and trillions
+6.7k Golang : Calculate diameter, circumference, area, sphere surface and volume
+5.9k Linux/Unix/PHP : Restart PHP-FPM
+9.5k Golang : How to control fmt or log print format?
+9.5k Golang : Create unique title slugs example
+7.1k Nginx : Password protect a directory/folder
+5.5k Golang : Generate Interleaved 2 inch by 5 inch barcode
+10.3k Golang : How to tokenize source code with text/scanner package?
+18.7k Golang : Aligning strings to right, left and center with fill example
+7.3k Javascript : How to get JSON data from another website with JQuery or Ajax ?
+18.9k Unmarshal/Load CSV record into struct in Go
+8.4k Golang : HttpRouter multiplexer routing example