How to remove duplicate elements from an array of strings in Go

1 Answer

0 votes
package main

import (
    "fmt"
)

func removeDuplicates(elements []string) []string {
    // Create a map to keep track of encountered elements
    encountered := map[string]bool{}
    // Create a slice to store the result
    result := []string{}

    for _, element := range elements {
        // Check if the element has been encountered before
        if !encountered[element] {
            // If not, add it to the map, and the resulting slice
            encountered[element] = true
            result = append(result, element)
        }
    }

    return result
}

func main() {
    elements := []string{"aaa", "bbb", "ccc", "ddd", "eee", "aaa", "www", "ddd", "bbb", "aaa"}
    
    fmt.Println(elements)
    fmt.Println(removeDuplicates(elements))
}



/*
run:

[aaa bbb ccc ddd eee aaa www ddd bbb aaa]
[aaa bbb ccc ddd eee www]

*/

 



answered Feb 6, 2025 by avibootz
...