remove elements from slice


Sajan Chandran:

I'm completely new to Golang and I'm trying to delete an element in one slice based on an element in another slice. E.g

Input slice:urlList := []string{"test", "abc", "def", "ghi"}

Remove elements of a slice:remove := []string{"abc", "test"}

Expected output slice:urlList := []string{"def", "ghi"}

This is what I have tried.

func main() {

    urlList := []string{"test", "abc", "def", "ghi"}
    remove := []string{"abc", "test"}
loop:
    for i, url := range urlList {
        for _, rem := range remove {
            if url == rem {
                urlList = append(urlList[:i], urlList[i+1:]...)
                continue loop
            }
        }
    }
    for _, v := range urlList {
        fmt.Println(v)
    }
}

But it's not working as I expected. I don't know what I'm thinking.

icza :

The problem is that when you remove an element from the original list, all subsequent elements are shifted . But the rangeloop doesn't know that you changed the underlying slice, and will increment the index as usual, which shouldn't be done even in this case, because then you're skipping an element.

And since the removelist contains 2 elements that were next to each other in the original list, the second element ( in this case) will not be checked and will not be removed."abc"

A possible solution is to not rangeuse in the outer loop, and when removing an element, you can manually decrease the index, since it will be automatically incremented by proceeding to the next iteration:i--

urlList := []string{"test", "abc", "def", "ghi"}
remove := []string{"abc", "test"}

loop:
for i := 0; i < len(urlList); i++ {
    url := urlList[i]
    for _, rem := range remove {
        if url == rem {
            urlList = append(urlList[:i], urlList[i+1:]...)
            i-- // Important: decrease index
            continue loop
        }
    }
}

fmt.Println(urlList)

output:

[def ghi]

Notice:

Since the outer loop contains nothing after the inner loop, you can replace label+continue with the simple break:

urlList := []string{"test", "abc", "def", "ghi"}
remove := []string{"abc", "test"}

for i := 0; i < len(urlList); i++ {
    url := urlList[i]
    for _, rem := range remove {
        if url == rem {
            urlList = append(urlList[:i], urlList[i+1:]...)
            i-- // Important: decrease index
            break
        }
    }
}

fmt.Println(urlList)

Try it out on the Go Playground .

Alternative

The alternative is to make the outer loop downward, so there is no need to manually decrease (or increase) the index variable, as the shifted elements are not affected (since the downward direction is already handled).

Related


remove elements from slice

Sax: Go doesn't provide any advanced functionality to remove elements from slices. I wrote a function that removes a given value from a slice in the way that is usually suggested here, but it produces very unexpected results. package main import "fmt" type A

remove elements from slice

Jorge Olivero: func main() { a := []string{"Hello1", "Hello2", "Hello3"} fmt.Println(a) // [Hello1 Hello2 Hello3] a = append(a[:0], a[1:]...) fmt.Println(a) // [Hello2 Hello3] } How does this delete trick with add function work? Seems

remove elements from slice

Sajan Chandran I'm completely new to Golang and I'm trying to delete an element in one slice based on an element in another slice. E.g Input slice:urlList := []string{"test", "abc", "def", "ghi"} Remove elements of a slice:remove := []string{"abc", "test"} Exp

remove elements from slice

Sajan Chandran: I'm completely new to Golang and I'm trying to delete an element in one slice based on an element in another slice. E.g Input slice:urlList := []string{"test", "abc", "def", "ghi"} Remove elements of a slice:remove := []string{"abc", "test"} Ex

remove elements from slice

Jorge Olivero: func main() { a := []string{"Hello1", "Hello2", "Hello3"} fmt.Println(a) // [Hello1 Hello2 Hello3] a = append(a[:0], a[1:]...) fmt.Println(a) // [Hello2 Hello3] } How does this delete trick with add function work? Seems

remove elements from slice

Sax: Go doesn't provide any advanced functionality to remove elements from slices. I wrote a function that removes a given value from a slice in the way that is usually suggested here, but it produces very unexpected results. package main import "fmt" type A

remove elements from slice

Jorge Olivero: func main() { a := []string{"Hello1", "Hello2", "Hello3"} fmt.Println(a) // [Hello1 Hello2 Hello3] a = append(a[:0], a[1:]...) fmt.Println(a) // [Hello2 Hello3] } How does this delete trick with add function work? Seems

remove elements from slice

Sajan Chandran I'm completely new to Golang and I'm trying to delete an element in one slice based on an element in another slice. E.g Input slice:urlList := []string{"test", "abc", "def", "ghi"} Remove elements of a slice:remove := []string{"abc", "test"} Exp

remove elements from slice

Sax: Go doesn't provide any advanced functionality to remove elements from slices. I wrote a function that removes a given value from a slice in the way that is usually suggested here, but it produces very unexpected results. package main import "fmt" type A

remove elements from slice

Jorge Olivero: func main() { a := []string{"Hello1", "Hello2", "Hello3"} fmt.Println(a) // [Hello1 Hello2 Hello3] a = append(a[:0], a[1:]...) fmt.Println(a) // [Hello2 Hello3] } How does this delete trick with add function work? Seems

Best way to remove selected elements from slice

Akhil K Nambiar I have one slice A and another slice B. Slice A contains n elements, slice B is a subset of slice A, where each element is a pointer to slice A. What is the cheapest way to remove all elements in A from B? After some googling, the only way I ca

Best way to remove selected elements from slice

Akhil K Nambiar I have one slice A and another slice B. Slice A contains n elements, slice B is a subset of slice A, where each element is a pointer to slice A. What is the cheapest way to remove all elements in A from B? After some googling, the only way I ca

Best way to remove selected elements from slice

Akhil K Nambiar I have one slice A and another slice B. Slice A contains n elements, slice B is a subset of slice A, where each element is a pointer to slice A. What is the cheapest way to remove all elements in A from B? After some googling, the only way I ca

remove slice elements in for

Siritinga: iThe idiomatic way to remove elements from a slice a(preserving order) seems to be: a = append(a[:i], a[i+1:]...) I'm wondering which is the best way to do this in a loop. As far as I understand it is not possible to use it in the following scopes:

remove slice elements in for

siritinga iThe idiomatic way to remove elements from a slice a(preserving order) seems to be: a = append(a[:i], a[i+1:]...) I'm wondering which is the best way to do this in a loop. As far as I understand it is not possible to use it in the following scopes: f

remove slice elements in for

Siritinga: iThe idiomatic way to remove elements from a slice a(preserving order) seems to be: a = append(a[:i], a[i+1:]...) I'm wondering which is the best way to do this in a loop. As far as I understand it is not possible to use it in the following scopes:

remove slice elements in for

Siritinga: iThe idiomatic way to remove elements from a slice a(preserving order) seems to be: a = append(a[:i], a[i+1:]...) I'm wondering which is the best way to do this in a loop. As far as I understand it is not possible to use it in the following scopes:

remove slice elements in for

Siritinga: iThe idiomatic way to remove elements from a slice a(preserving order) seems to be: a = append(a[:i], a[i+1:]...) I'm wondering which is the best way to do this in a loop. As far as I understand it is not possible to use it in the following scopes:

remove slice elements in for

Siritinga: iThe idiomatic way to remove elements from a slice a(preserving order) seems to be: a = append(a[:i], a[i+1:]...) I'm wondering which is the best way to do this in a loop. As far as I understand it is not possible to use it in the following scopes:

remove slice elements in for

Siritinga: iThe idiomatic way to remove elements from a slice a(preserving order) seems to be: a = append(a[:i], a[i+1:]...) I'm wondering which is the best way to do this in a loop. As far as I understand it is not possible to use it in the following scopes:

MongoDB slice - remove last n elements from nested array

William Suppose I have the following array: { data: [1, 0, 4, 0, 0, 4, 1, 3, 0, 1, 0, 2, 2, 0, 1, 1, 0, 2, 0, 4, 1, 1, 0, 1, 1, 0] } If you want to select all but the last three elements, you can use the solution suggested here db.collection.aggregate([

MongoDB slice - remove last n elements from nested array

William Suppose I have the following array: { data: [1, 0, 4, 0, 0, 4, 1, 3, 0, 1, 0, 2, 2, 0, 1, 1, 0, 2, 0, 4, 1, 1, 0, 1, 1, 0] } If you want to select all but the last three elements, you can use the solution suggested here db.collection.aggregate([

MongoDB slice - remove last n elements from nested array

William Suppose I have the following array: { data: [1, 0, 4, 0, 0, 4, 1, 3, 0, 1, 0, 2, 2, 0, 1, 1, 0, 2, 0, 4, 1, 1, 0, 1, 1, 0] } If you want to select all but the last three elements, you can use the solution suggested here db.collection.aggregate([

MongoDB slice - remove last n elements from nested array

William Suppose I have the following array: { data: [1, 0, 4, 0, 0, 4, 1, 3, 0, 1, 0, 2, 2, 0, 1, 1, 0, 2, 0, 4, 1, 1, 0, 1, 1, 0] } If you want to select all but the last three elements, you can use the solution suggested here db.collection.aggregate([

MongoDB slice - remove last n elements from nested array

William Suppose I have the following array: { data: [1, 0, 4, 0, 0, 4, 1, 3, 0, 1, 0, 2, 2, 0, 1, 1, 0, 2, 0, 4, 1, 1, 0, 1, 1, 0] } If you want to select all but the last three elements, you can use the solution suggested here db.collection.aggregate([