OneBite.Dev - Coding blog in a bite size

remove duplicates from an array in Go

Code snippet on how to remove duplicates from an array in Go

package main

import (
	"fmt"
)

func main() {
	arr := []int{1, 2, 3, 4, 1, 2, 3}
	arrNoDuplicate := removeDuplicates(arr)
	fmt.Println(arrNoDuplicate)
}

func removeDuplicates(arr []int) []int {
	newArr := make([]int, 0)
	for _, i := range arr {
		if !contains(arr, i) {
			newArr = append(newArr, i)
		}
		return newArr
	}
}

func contains(arr []int, i int) bool {
	for _, a := range arr {
		if i == a {
			return true
		}
	}
	return false
}

This code uses a loop and the contains() function to remove duplicate values from an array, arr. The code first declares an empty array named newArr, which will contain the values with all duplicate entries removed. Then it iterates through that array, and for each value, it checks if it already exists in the array with the loop and contains() function. If it does not exist, it will be added to the newArr. Finally, the program prints out the result, the new array containing only values that are unique and had no duplicates.

go