Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find and delete elements from slice in golang

Tags:

slice

go

I have slice of numbers like [1, -13, 9, 6, -21, 125]. I want to find elements that are less than zero then delete them.

It can be done by straightforward way: just iterate through slice and if element less than zero -> delete it. But it computationally costly because of possible slice changing on each step.

Is there any elegant way of doing it like numpy.where(array, condition) and numpy.delete?

like image 980
Kenenbek Arzymatov Avatar asked Oct 20 '25 12:10

Kenenbek Arzymatov


1 Answers

Copy the surviving elements to the beginning of the slice, and reslice when done.

p := []int{1, -13, 9, 6, -21, 125}
j := 0

for _, n := range p {
    if n >= 0 {
        p[j] = n
        j++
    }
}
p = p[:j]

No memory is allocated, but the original slice is modified. If you cannot modify the original slice, then allocate and copy to a new slice:

p := []int{1, -13, 9, 6, -21, 125}
j := 0
q := make([]int, len(p))
for _, n := range p {
    if n >= 0 {
        q[j] = n
        j++
    }
}
q = q[:j] // q is copy with numbers >= 0

playground example