shishh03
shishh03

Reputation: 57

GoLang: Check if item from Slice 1 contains in Slice 2. If it does, remove Slice 2

I have a string array: slice1 [][]string. I get the values I want using a for loop:

for _, i := range slice1 { //[string1 string2]
    fmt.Println("server: ", i[1]) //only want the second string in the array.
}

Now I have another string array: slice2 [][]string I get its values using a for loop as well:

for _, value := range output { //
    fmt.Println(value) //Prints: [ 200K, 2, "a", 22, aa-d-2, sd , MatchingString, a ]
}

I want to iterate through slice1 and check if the string2 matches "MatchingString" in Slice2. If it does, don't print the value array.

I created a for loop again to do this but its not working:

for _, value := range slice2 {
    for _, i := range slice1 {
        if strings.Contains(value[0], i[1]) {
            //skip over
        } else {
            fmt.Println(value)
        }
    }
}

Here's a sample code: https://play.golang.org/p/KMVzB2jlbG Any idea on how to do this? Thanks!

Upvotes: 0

Views: 5481

Answers (1)

fuglede
fuglede

Reputation: 18201

If I'm reading your question correctly, you are trying to print all those subslices of slice2 that have the property that none of the strings within are the second element of a slice in slice1. If so, you can obtain that through

Slice2Loop:
    for _, value := range slice2 {
        for _, slice2string := range value {
            for _, i := range slice1 {
                if slice2string == i[1] {
                    continue Slice2Loop
                }
            }
        }
        fmt.Println(value)
    }

Upvotes: 1

Related Questions