0

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]
khilmi aminudin
  • 117
  • 1
  • 4
  • There are two easy ways: one is sort the slice and loop over all entries, checking if the actual element is different from the previous. Another possibility is to use a map like you can see below. The map solution is more readable IMHO – Tiago Peczenyj Apr 14 '22 at 09:27

1 Answers1

0

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

Amila Senadheera
  • 12,229
  • 15
  • 27
  • 43