UniqueBy function for arrays/slices in Go

How to write a functional UniqueBy function in golang using generics, including a unit test. Stop writing this by hand every single time!


UniqueBy applies a function to each element in the input slice and returns a new slice containing the unique elements based on the function’s return value. The function f takes an element of type A and returns a key of type K.

func UniqueBy[A any, K comparable](input []A, f func(A) K) []A {
	seen := make(map[K]bool)
	var result []A
	for _, v := range input {
		key := f(v)
		if !seen[key] {
			seen[key] = true
			result = append(result, v)
		}
	}
	return result
}

and this is a unittest for the function:

func TestUniqueBy(t *testing.T) {
	input := []string{"apple", "banana", "cherry", "date", "elderberry"}
	f := func(a string) int {
		return len(a)
	}
	expected := []string{"apple", "banana", "date", "elderberry"}
	result := util.UniqueBy(input, f)
	if !reflect.DeepEqual(expected, result) {
		t.Errorf("Expected %v, got %v", expected, result)
	}
}

Linked Technologies

What it's made of

illustration of Go
Go

Fast, simple, and efficient. Ideal for solopreneurs, Go's straightforward syntax and powerful performance allow for quick development and deployment.

Linked Categories

Where it's useful

illustration of Data Engineering
Data Engineering

Explore the essentials of Data Engineering, delving into how data systems are built and maintained. From organizing data flows to automating complex data processes, discover the tools and techniques that make data easily accessible and useful for everyday projects and insights.