How do I remove duplicate values from slice with Go Lang

Last updated Dec 05, 2021

In this article, the program to remove duplicates is created with Go programming language.

These are the steps to remove duplicates.

  1. Create a map and slice. Map is used to store key value pairs whilst slice is used to store the result.
  2. Insert every key value pairs into map.
  3. Get all keys from map then store into slice.

This is the implementation.

func removeDuplicates(numbers []int) []int {
// create a slice to store the result of removed duplicates
var result []int = []int{}

// create a map to store key value pairs
var removed map[int]int = map[int]int{}

// insert key value pairs into map
for _, number := range numbers {
removed[number] = number
}

// get all keys from map
for key := range removed {
result = append(result, key)
}

// return the result
return result
}

 

The removeDuplicates() is used in main function.

package main

import (
"fmt"
)

func main() {
  var numbers []int = []int{5, 6, 1, 9, 1, 3, 7, 3, 9, 7, 6, 4, 3, 2, 9, 9, 9}

  var result []int = removeDuplicates(numbers)

  fmt.Println("The result: ", result)
}

func removeDuplicates(numbers []int) []int {
var result []int = []int{}

var removed map[int]int = map[int]int{}

for _, number := range numbers {
removed[number] = number
}

for key := range removed {
result = append(result, key)
}

return result
}

 

Output.

The result:  [7 4 2 5 6 1 9 3]

 

I hope this article is helpful to learn about creating program to remove duplicates in Go.


Article Contributed By :
https://www.rrtutors.com/site_assets/profile/assets/img/avataaars.svg

156 Views

Subscribe For Daily Updates

Flutter Questions
Android Questions