Skip to content

Golang Merge Slices Unique – Remove Duplicates

You want to remove duplicates from your slice, and maybe you have more than one slice to merge and get the uniques from them! Let me help you with this helper function I made:

// If you have only one slice
UniqueNumbers(firstSlice)

// If you have more than one slice
UniqueNumbers(firstSlice, secondSlice, thirdSlice)

Whit this function you can merge and get the unique items from one or more slices in one call:

package main

import "fmt"

func main() {
	firstSlice := []int{1, 2, 3, 3, 3}
	secondSlice := []int{2, 3, 4, 5, 5, 6}

	// remove duplicate from a slice
	fmt.Println(UniqueInts(firstSlice))

	// Merge (append) slices and remove duplicate from them!
	fmt.Println(UniqueInts(firstSlice, secondSlice))

}

func UniqueInts(intSlices ...[]int) []int {
	uniqueMap := map[int]bool{}

	for _, intSlice := range intSlices {
		for _, number := range intSlice {
			uniqueMap[number] = true
		}
	}

	// Create a slice with the capacity of unique items
	// This capacity make appending flow much more efficient
	result := make([]int, 0, len(uniqueMap))

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

	return result
}

Leave a Reply

Your email address will not be published. Required fields are marked *