Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,923 questions

51,856 answers

573 users

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

Related questions

2 answers 115 views
1 answer 89 views
1 answer 151 views
1 answer 150 views
1 answer 196 views
1 answer 57 views
...