Challenge 04 - Checking for Duplicates

In this challenge, we are going to be looking at how you can effectively filter out the duplicate entries from a slice in Go.

The task will be to implement the FilterDuplicates function so that it returns a slice of type string which contains only the unique names of developers retrieved from the inputted list.

Example:

// input
[]Developers{
  Developer{Name: "Elliot"},
  Developer{Name: "Alan"},
  Developer{Name: "Jennifer"},
  Developer{Name: "Graham"},
  Developer{Name: "Paul"},
  Developer{Name: "Alan"},
}

// output
[]string{
  "Elliot",
  "Alan",
  "Jennifer",
  "Graham",
  "Paul",
}

Hints

You may wish to use a map in your function in order to check if elements have already been seen by our function.

View Solution
package main

import "fmt"

type Developer struct {
	Name string
	Age  int
}

func FilterUnique(developers []Developer) []string {
	uniqueMap := make(map[string]bool)
	var uniqueNames []string

	for _, dev := range developers {
		if _, exists := uniqueMap[dev.Name]; !exists {
			uniqueMap[dev.Name] = true
			uniqueNames = append(uniqueNames, dev.Name)
		}
	}
	return uniqueNames
}

func main() {
	fmt.Println("Filter Unique Challenge")
}

Further Reading:

If you like this challenge then you may also enjoy some of the other challenges on the site:


Other Challenges