Remove elements from a slice, then return the removed and remaining elements


John Balvin Arias:

I just want a function that has a slice of struct type "t", returns the return value which is the element I'm looking for, and the rest I tried with a partial solution to the problem like this: delete elements in a slice but for a strange reason it doesn't work as expected https://play.golang.org/p/tvJwkF5c_tj

    func main() {
    var names = []string{"john", "julio", "pepito","carlos"}
    fmt.Println(getMe("john", names))
}
func getMe(me string, names []string) (string, []string, bool) {
    for i := range names {
        if names[i] == me {
            return names[i], append(names[:i], names[i+1:]...), true
        }
    }
    return "", nil, false
}

But the result gives me:

julio [julio pepito carlos] true

UPDATE: https://play.golang.org/p/1xbu01rOiMg taking answer from @Ullaakut If I do: , it changes the original slice, so this doesn't work for me, I don't want to change the slice because I slightly will be used laterappend(names[:i], names[i+1:]...)

Quote:

Just use the range to get the value and the index instead of accessing the value by using the index.

package main

import (
    "fmt"
)

func main() {
    var names = []string{"john", "julio", "pepito", "carlos"}
    name, newNames, _ := getMe("john", names)

    fmt.Println("extracted name:\t\t\t\t", name)
    fmt.Println("new slice without extracted name:\t", newNames)
    fmt.Println("old slice still intact:\t\t\t", names)
}

func getMe(me string, names []string) (string, []string, bool) {
    var newSlice []string

    for i := 0; i < len(names); i++ {
        if names[i] == me {
            newSlice = append(newSlice, names[:i]...)
            newSlice = append(newSlice, names[i+1:]...)
            return names[i], newSlice, true
        }
    }

    return "", nil, false
}

output

extracted name:                        john
new slice without extracted name:      [julio pepito carlos]
old slice still intact:                [john julio pepito carlos]

See playground example

Edited after request for a faster version: it's much faster to use a manual instead of a range loop. Since you need to create a new slice with no elements, it is necessary to build a new slice inside the function, which always requires some processing power.

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

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

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

How to return slice elements from mongodb array?

Irfan Khabib | I have a list of data in an array of size 250 MB. On every query, even though I'm slicing the data, the full 250 is downloaded. this is my code DomainsApi.findOne({}, {auction_list:{$slice:[10, 20]}}, (err, doc)=>{ if(doc){ console.log(doc

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:

Remove array elements and move remaining elements to the left

Valtana What I want to achieve is to delete an array element by its index and shift the remaining elements to the left. So, for example, deleteshifting the second element of the ['a','b','c','d']array returns the array ['a','c','d']. I managed to do this using

Remove array elements and move remaining elements to the left

Valtana What I want to achieve is to delete an array element by its index and shift the remaining elements to the left. So, for example, deleteshifting the second element of the ['a','b','c','d']array returns the array ['a','c','d']. I managed to do this using