Home > front end >  How to compare 2 string slices and get elements present in 1st slice and not in 2nd slice into an an
How to compare 2 string slices and get elements present in 1st slice and not in 2nd slice into an an

Time:11-08

I have 3 string slices:

enp_slice := []string{"10.10.10.10", "10.10.10.11"}
cachedenp_slice := []string{"10.10.10.10", "10.10.10.11", "10.10.10.12"}
result := []string{}

I want to compare the 2 string slices and get distict elements in both of them and store them into the 3rd slice(element present in cachedenp_slice but not in enp_slice) like following:

result = ["10.10.10.12"]

CodePudding user response:

This should work for you.
I iterated over the two slices and take the elements of the second slice that are not present in the first one. I used a bool variable called isFound to understand if the current item was found or not. Below you can find the code:

package main

import "fmt"

func main() {
    enp_slice := []string{"10.10.10.10", "10.10.10.11"}
    cachedenp_slice := []string{"10.10.10.10", "10.10.10.11", "10.10.10.12"}
    result := []string{}

    for _, v := range cachedenp_slice {
        isFound := false
        for _, w := range enp_slice {
            if v == w {
                isFound = true
                break
            }
        }
        if !isFound {
            result = append(result, v)
        }
    }

    fmt.Printf("%v\n", result)
}

Let me know if works also for you.

CodePudding user response:

Another option is to convert the target slice to map, then check the origin slice with this map

Sample codes

func main() {
    enp_slice := []string{"10.10.10.10", "10.10.10.11"}
    cachedenp_slice := []string{"10.10.10.10", "10.10.10.11", "10.10.10.12"}
    fmt.Println(diffSlice(cachedenp_slice, enp_slice))
}

func diffSlice(origin, target []string) []string {
    m := make(map[string]struct{}, len(target))
    for _, v := range target {
        m[v] = struct{}{}
    }

    var result []string
    for _, v := range origin {
        if _, ok := m[v]; !ok {
            result = append(result, v)
        }
    }

    return result
}

https://go.dev/play/p/wOM5MZnZrcd

  •  Tags:  
  • go
  • Related