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
+4.2k Golang : Dealing with backquote
+17.3k Golang : How to Set or Add Header http.ResponseWriter?
+5k How to let Facebook Login button redirect to a particular URL ?
+10.6k CodeIgniter : "Fatal error: Cannot use object of type stdClass as array" message
+16.9k Golang : convert int to string
+6.1k Golang : Detect Pascal, Kebab, Screaming Snake and Camel cases
+16.5k Golang : Clean up null characters from input data
+2.8k Linux : How to set root password in Linux Mint
+12.6k Golang : Generate QR codes for Google Authenticator App and fix "Cannot interpret QR code" error
+6.8k Golang : Scramble and unscramble text message by randomly replacing words
+7.8k Linux : How to install driver for 600Mbps Dual Band Wifi USB Adapter
+15.2k Golang : When to use init() function?