Skip to content
Node: arr.filter(fn)github.com/sahilkhaire/gox/slice

Filter

Overview

Keeps elements matching a predicate — same as Array.filter. Returns a new slice containing only matching items.

If you are coming from Node.js, the closest pattern is arr.filter(fn).

Signature

go
func Filter[T any](in []T, fn func(T) bool) []T

Compare: Node.js · Standard Go · gox

js
const adults = users.filter(u => u.age >= 18);
go
var adults []User
for _, u := range users {
    if u.Age >= 18 {
        adults = append(adults, u)
    }
}
go
import "github.com/sahilkhaire/gox/slice"

adults := slice.Filter(users, func(u User) bool { return u.Age >= 18 })

Example

go
import "github.com/sahilkhaire/gox/slice"

adults := slice.Filter(users, func(u User) bool { return u.Age >= 18 })

Tips

Combine with slice.Map for filter-then-map pipelines without nested loops.

Standard library alternative

Use the standard library directly:

go
var adults []User
for _, u := range users {
    if u.Age >= 18 {
        adults = append(adults, u)
    }
}

Back to slice package overview

MIT Licensed · Built for Node.js developers moving to Go