[Go]Remove duplicate elements in array/slice

In python to remove duplicates we use unordered iterable set() but in Go it is not so straight forward, there is no package to do this i think… So here’s an example on how duplicate elements are removed.

Algorithm
A flag variable is created using make(), flag is a map that has a key that is string and a Boolean as its value, map[string]bool. Map is like struct except that map can only have one value type for key and one value type of value, in python the equivalent is dictionary which has key/value pairs.

Since there is no value in map object flag, the key is nil and the bool is false.

The string slice will then be evaluated one element by another element, for each element it is check if there is a false, if it has a false change to true, in this way each element that has already occurred will definitely be marked true, hence repeated element will not be appended to the new string slice which will be returned as new unique slice.

package main

import "fmt"

func main() {
	// name list that has duplicated names
	nameSlice := []string{
		"Cyrus",
		"Alex",
		"Cyrus",
		"Bobby",
		"June",
		"James",
		"James",
		"Cyrus",
		"James",
		"Jeffery",
		"Bobby",
		"April",
		"April",
		"April",
	}

	uniqueNames := makeUnique(nameSlice)
	fmt.Println(uniqueNames)
	for i:= 0; i < len(uniqueNames); i++ {
		fmt.Printf("Name in index %d is %s\n", i, uniqueNames[i])
	}
}

func makeUnique(names []string) []string {
	// if the name occurs the flag changes to true.
	// hence all name that has already occurred will be true.
	flag := make(map[string]bool)
	var uniqueNames []string
	for _, name := range names {
		if flag[name] == false {
			flag[name] = true
			uniqueNames = append(uniqueNames, name)
		}
	}
	// unique names collected
	return uniqueNames
}

Result
go2.PNG

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s