Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

dictionary

go

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!

like image 582
Cynial Avatar asked Oct 24 '25 17:10

Cynial


1 Answers

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.

like image 124
ANisus Avatar answered Oct 26 '25 09:10

ANisus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!