How to remove duplicate values from slice in Go

1 Answer

0 votes
package main
  
import (
"fmt"
)
  
func uniqueSlice(slice []int) []int {
    keys := make(map[int]bool)
    list := []int{} 
    for _, n := range slice {
       if _, b := keys[n]; !b {
            keys[n] = true
            list = append(list, n)
        }
    }    
    return list
}
  
func main() {
    slice := []int{5, 6, 2, 1, 1, 5, 6, 8, 2, 2, 2, 9}
    
    fmt.Println(slice) 
    
    uslice := uniqueSlice(slice)
    
    fmt.Println(uslice)
}
  
  
  
  
/*
run:
  
[5 6 2 1 1 5 6 8 2 2 2 9]
[5 6 2 1 8 9]
  
*/

 



answered Aug 14, 2020 by avibootz

Related questions

...