Removing duplicate elements from an array/slice in Golang

Recently I encountered an issue where I was supposed to merge two slices of strings into one so that the resulting slice should not contain any element from first or the second more than once. For example, A = [‘x’,’y’,’z’] and B = [‘x’,’p’,’q’]C = [‘p’,’x’,’z’,’q’,’y’].

So here I’m doing what is mentioned in the topic of this blog on the final slice that is a=obtained by just appending both the slices. This can be done by- c:= append(a, b…)

Algorithm for the solution:-

  1. append both the slices and form the final slice.
  2. Create a hash map from string to int. (you can use something else as value too)
  3. Iterate through slice and map each element to 0. (or any other thing)
  4. Now finally iterate through the map and append each key of the map to a new slice of strings. Since any duplicate value too will be mapped to the same number as the previous one, hence all the keys will be unique.
package main
import (
	"fmt"
)
func appendCategory(a []string, b []string) []string {
	check := make(map[string]int)
	d := append(a, b...)
	res := make([]string,0)
	for _, val := range d {
		check[val] = 1
	}
	for letter, _ := range check {
		res = append(res,letter)
	}
	return res
}
func main() {
	a := []string{"x", "y", "z"}
	b := []string{"x", "p", "q"}
	c := appendCategory(a, b)
	fmt.Println(c)
}