Kenenbek Arzymatov
Kenenbek Arzymatov

Reputation: 9109

Find and delete elements from slice in golang

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?

Upvotes: 4

Views: 12666

Answers (1)

Thundercat
Thundercat

Reputation: 120941

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

Upvotes: 12

Related Questions