dictionarygo

Is there a way to unique a map[string]interface{} for golang?


Just like array_unique function for php:

$input = array("a" => "green", "red", "b" => "green", "blue", "red");
$result = array_unique($input);
print_r($result);

Output:

Array
(
    [a] => green
    [0] => red
    [1] => blue
)

Thx!


Solution

  • There is no built in way to do it, so you need to make a function yourself.

    If you want to make a general function, you will have to use reflect. If you have a specific map type, then you can make it more easily:

    package main
    
    import (
        "fmt"
    )
    
    func Unique(m map[string]string) map[string]string {
        n := make(map[string]string, len(m))
        ref := make(map[string]bool, len(m))
        for k, v := range m {
            if _, ok := ref[v]; !ok {
                ref[v] = true
                n[k] = v
            }
        }
    
        return n
    }
    
    func main() {
        input := map[string]string{"a": "green", "0": "red", "b": "green", "1": "blue", "2": "red"}
        unique := Unique(input)
        fmt.Println(unique)
    }
    

    Possible output

    map[a:green 0:red 1:blue]

    Playground

    Note

    Because maps do not maintain order, you cannot know which keys will be stripped away.