Go filter slice example

In this example, we will show you how to create a function to filter an array in Go with an example

A filtering operation processes a data structure (e.g. an array) and produces a new data structure containing exactly those elements for which the given predicate returns true.

Go filter slice example

In the following example, we filter out positive values.


package main

import (
    "fmt"
)

func main() {

    vals := []int{-2, -1, 1, 4, 5, -3, -5, 9}
    positive := []int{}

    for i := range vals {
        if vals[i] > 0 {
            positive = append(positive, vals[i])
        }
    }

    fmt.Println(positive)
}

Output:

[1 4 5 9]

Note that we have an array of integers. We create a new array from the existing one having only its positive values.

We go over the elements of the array with a for a loop. We test each element if it is greater than zero. All the elements that satisfy the condition are copied to the new positive slice. The original slice is not modified:

for i := range vals {
    if vals[i] > 0 {
        positive = append(positive, vals[i])
    }
}