Golang program that removes duplicates, ignores order


When working with slices in Golang, it's common to need to remove duplicate elements from the slice. While there are many ways to do this, one approach that can be particularly useful is to remove duplicates while ignoring the order of the elements. This can be useful, for example, when you want to compare two slices for equality without caring about the order of the elements.

In this article, we'll explore a simple Golang program that removes duplicates from a slice while ignoring the order of the elements. We'll break down the program step by step to explain how it works.

Step 1: Define the removeDuplicates function

We'll start by defining a function called removeDuplicates that takes a slice of integers as input and returns a new slice containing only the unique elements. Within this function, we declare two variables: unique, which will hold the unique elements, and seen, which is a map that will help us keep track of which elements we've already seen.

func removeDuplicates(elements []int) []int {
   unique := []int{}
   seen := map[int]bool{}
   // ...
}

Step 2: Loop through the input slice and check for duplicates

Next, we'll loop through the input slice using a for loop, iterating over each element in the slice. For each element, we check whether it is already present in the seen map. If it is not present, we add it to the unique slice and mark it as seen in the map.

for _, element := range elements {
   if _, ok := seen[element]; !ok {
      unique = append(unique, element)
      seen[element] = true
   }
}

Step 3: Return the new slice containing unique elements

Finally, we return the unique slice, which now contains only the unique elements from the input slice.

return unique

Putting it all together, the complete removeDuplicates function looks like this:

Example

package main

import "fmt"

func removeDuplicates(elements []int) []int {
   unique := []int{}
   seen := map[int]bool{}
   for _, element := range elements {
      if _, ok := seen[element]; !ok {
         unique = append(unique, element)
         seen[element] = true
      }
   }
   return unique
}

func main() {
   // Example usage
   nums := []int{1, 2, 3, 2, 4, 3}
   uniqueNums := removeDuplicates(nums)
   fmt.Println(uniqueNums)
}

Output

[1 2 3 4]

Conclusion

In this article, we've explored a simple Golang program that removes duplicates from a slice while ignoring the order of the elements. By breaking down the program step by step, we've shown how to use a map to keep track of which elements have been seen, and how to create a new slice containing only the unique elements. This technique can be useful in a variety of contexts where you need to remove duplicates while ignoring the order of the elements in the slice.

Updated on: 18-Apr-2023

60 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements