'how to get lonely value from a slice golang [duplicate]

I want to create a function that can retrieve data that has no duplicates from a slice

an example of a slice that will be processed:

number1 := []int{3,4,5,4,3}
number2 := []int{3,4,5,6,4,3}

expected result :

res1 = []int{5}
res2 = []int{5,6}

i have do something like this

func unique(arg []int) []int {
    var inResult = make(map[int]bool)
    var result []int

    for _, value := range arg {
        if _, ok := inResult[value]; !ok {
            inResult[value] = true
            result = append(result, value)
        } else {
            inResult[value] = false
        }
    }
    fmt.Println(inResult)
    return result
}

func main() {   arg := []int{6, 6, 7, 1, 2, 3, 4, 5, 3, 2, 1}
    res := unique(arg)
    fmt.Println(res)
}

how to get the key from map where the value is true?

map[1:false 2:false 3:false 4:true 5:true 6:false 7:true]
[6 7 1 2 3 4 5]


Solution 1:[1]

You can filter out the keys like this.

  1. Remove the following line in if block. It should be done after the complete iteration.
result = append(result, value)
  1. Filter the keys with having true value before returning result.
for key, value := range inResult {
    if value {
        result = append(result, key)
    }
}

Go Playground

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Amila Senadheera