Home > Back-end >  How to remove elements from other_names that are equal to elements in names?
How to remove elements from other_names that are equal to elements in names?

Time:11-05

  1. Compare slice 'names' with slice 'other_names';
  2. If slice of slice 'names'(names[1]) have same items that slice of slice 'other_names'(other_name[0][1]), we should delete that slice.

So, I need to compare 'names' and 'other_names' and delete slice of the slice if it have same elements.

Simple. How to delete 'other_name[0][1]', it should be:

var other_names = [][][]string{
        {
            {"Sony", "Bond"},
            {"Piter", "Nina"},
        },
    }

The following code works, but not correctly =>

func Duplicate() {

    var names = [][]string{
        {"Malder", "Carl"},
        {"Adam", "Kent"},
    }

    var other_names = [][][]string{
        {
            {"Sony", "Bond"},
            {"Adam", "Kent"},
            {"Piter", "Nina"},
        },
    }

    // s := append(s, copies)

    var origl [][]string
    for i := 0; i < len(names); i   {
        // fmt.Println(names[i][1])
        for v := 0; v < len(copies); v   {
            for d := 0; d < len(copies[v]); d   {
                if names[i][1] == copies[v][d][1] {
                    // fmt.Println("[copy index]", d, copies[v][d])
                    origl = copies[v][:d]
                    // fmt.Println(origl)
                }
            }
        }
    }
    fmt.Println(origl)
}

CodePudding user response:

How to delete 'other_name[0][1]

Think of this as a filtering problem, not a deletion problem. Construct a slice of what you want to keep.

Write a function to determine whether a []string is contained in a [][]string.

func contains(needle []string, haystack [][]string) bool {
hloop:
    for _, h := range haystack {
        if len(needle) != len(h) {
            continue hloop
        }
        for i := range needle {
            if needle[i] != h[i] {
                continue hloop
            }
        }
        return true
    }
    return false
}

Copy elements from the original slice to the result slice only if the element in the original slice is not contained in names.

result := other_names[0][:0]
for _, other_name := range other_names[0] {
    if !contains(other_name, names) {
        result = append(result, other_name)
    }
}
other_names[0] = result
  •  Tags:  
  • go
  • Related