Array.filter
func Array.filter[T](xs: Array[T], f: func(T): bool): Array[T]Array.filter returns a new array holding the elements of xs that f accepts, in order.
Details
- Returns a new array;
xsis unchanged, even whenfaccepts every element. - Calls
fonce per element, from first to last, and never stops early. - On a sequence,
.filterisIter.filter, which is lazy.
Basic examples
Keep the even numbers:
Array.filter([1, 2, 3, 4, 5, 6], { x % 2 == 0 }) // [2, 4, 6]Keep the words longer than three characters:
Array.filter(["ant", "beetle", "fly", "wasp"], { x.length() > 3 }) // ["beetle", "wasp"]Scope
An empty array gives an empty array, and so does a predicate that accepts nothing:
let empty: Array[int] = []
empty.filter({ x > 0 }) // []
[1, 2, 3].filter({ false }) // []Filter the characters of a string by splitting it into graphemes first:
"héllo wörld" | String.graphemes() | Array.filter({ x != "l" }) // ["h", "é", "o", " ", "w", "ö", "r", "d"]Test a record through its fields:
type Task = { title: string, done: bool }
let tasks = [Task{ title: "write", done: true }, Task{ title: "test", done: false }]
tasks.filter({ !x.done }) // [Task{ title: "test", done: false }]Drop the null elements of a nullable array:
let scores: Array[int | null] = [90, null, 75, null]
scores.filter({ x != null }) // [90, 75]Pick one member of a union with is:
type Circle = { radius: float64 }
type Rect = { width: float64, height: float64 }
type Shape = Circle | Rect
let shapes: Array[Shape] = [Circle{ radius: 1.0 }, Rect{ width: 2.0, height: 3.0 }]
shapes.filter({ x is Circle }) // [Circle{ radius: 1.0 }]Filter by index through Array.entries:
["a", "b", "c", "d"]
| Array.entries()
| Array.filter({ x.index % 2 == 0 })
| Array.map({ x.value }) // ["a", "c"]Pass a named function or a function on a type instead of a lambda:
func isVowel(s: string): bool { "aeiou".contains(s) }
"anthill".graphemes().filter(isVowel) // ["a", "i"]
["a", "", "b"].filter(String.isEmpty) // [""]An anonymous function names its parameter, which helps when the body nests another lambda:
let banned = ["spam", "junk"]
let subjects = ["hello", "cheap spam", "lunch?"]
subjects.filter(func(s: string): bool { !banned.some({ s.contains(x) }) }) // ["hello", "lunch?"]A closure reads the variables it captures:
let limit = 10
let prices = [4, 12, 9, 30]
prices.filter({ x <= limit }) // [4, 9]Call it through . or in a pipe:
[1, 2, 3, 4].filter({ x > 2 }) // [3, 4]
[1, 2, 3, 4] | Array.filter({ x < 3 }) // [1, 2]Applications
Chain filter with map to select and then transform:
type User = { name: string, active: bool }
let users = [
User{ name: "Ann", active: true },
User{ name: "Bob", active: false },
User{ name: "Cid", active: true },
]
users.filter({ x.active }).map({ x.name }) // ["Ann", "Cid"]Keep the lines of a text that are not blank or comments:
let text = "# config\nhost = localhost\n\nport = 8080\n"
text.split("\n").filter({ x.trim() != "" && !x.startsWith("#") }) // ["host = localhost", "port = 8080"]Remove one value from an array by keeping everything else:
var tags = ["red", "green", "blue"]
tags = tags.filter({ x != "green" })
tags // ["red", "blue"]Split an array in two with a predicate and its negation:
let temps = [18, 25, 31, 12, 27]
let warm = temps.filter({ x >= 25 })
let cool = temps.filter({ x < 25 })
warm // [25, 31, 27]
cool // [18, 12]Report the failed checks of a test run:
type Check = { name: string, ok: bool }
let checks = [
Check{ name: "parse", ok: true },
Check{ name: "format", ok: false },
Check{ name: "lint", ok: false },
]
for c in checks.filter({ !x.ok }) {
println("FAIL ${c.name}")
}FAIL format
FAIL lintProperties and relations
The result is never longer than xs, and every element of it passes f:
let xs = [5, 8, 1, 9, 4]
let f: func(int): bool = { x > 4 }
let kept = xs.filter(f)
assert(len(kept) <= len(xs))
assert(kept.every(f))The length of the result is what Array.countWhere counts:
let xs = ["a", "bb", "ccc", "dd"]
assert(len(xs.filter({ x.length() == 2 })) == xs.countWhere({ x.length() == 2 }))Filtering by f and by its negation splits xs with nothing lost:
let xs = [3, 6, 9, 12, 15]
let yes = xs.filter({ x % 2 == 0 })
let no = xs.filter({ x % 2 != 0 })
assert(len(yes) + len(no) == len(xs))Filtering twice by the same predicate changes nothing the second time:
let xs = [1, 2, 3, 4, 5]
let once = xs.filter({ x % 2 == 1 })
assert(once.filter({ x % 2 == 1 }) == once)The result is a new array even when it holds every element, so changing it leaves xs as it was:
let xs = [1, 2, 3]
let all = xs.filter({ true })
assert(all == xs)
assert(!Array.same(all, xs))
all[0] = 9
assert(xs == [1, 2, 3])f runs once for each element, in order, even after it has accepted or rejected some:
let seen: Array[int] = []
[3, 1, 4, 1].filter({ seen.push(x); x > 1 }) // [3, 4]
seen // [3, 1, 4, 1]A callback that pushes to xs does not change what the call visits:
let xs = [1, 2, 3]
xs.filter({ xs.push(10); x > 1 }) // [2, 3]
xs // [1, 2, 3, 10, 10, 10]Possible issues
Array.filter returns a new array and leaves xs as it was. A call whose result is thrown away does not change xs; assign the result, as in xs = xs.filter(...):
let xs = [3, 1, 2]
xs.filter({ x > 1 })
println(xs)[3, 1, 2]The predicate must return a bool. Ant has no truthy values, so an int is a compile error:
let counts = [0, 2, 0, 5]
let nonZero = counts.filter({ x }) // error: cannot use int where bool is expectedThe result keeps the element type of xs. Filtering out null gives an Array[int | null], not an Array[int]:
let scores: Array[int | null] = [90, null, 75]
let ints: Array[int] = scores.filter({ x != null })
// error: cannot use Array[int | null] where Array[int] is expectedUse Array.flatMap instead. Inside the lambda the test on x narrows it, so the arrays it returns hold ints:
let scores: Array[int | null] = [90, null, 75]
let ints: Array[int] = scores.flatMap({ if x == null { [] } else { [x] } })
ints // [90, 75]The same holds for a union: filter with is Circle still gives an Array[Shape], whose fields are those every member has:
type Circle = { radius: float64 }
type Rect = { width: float64, height: float64 }
type Shape = Circle | Rect
let shapes: Array[Shape] = [Circle{ radius: 1.0 }, Rect{ width: 2.0, height: 3.0 }]
let radii = shapes.filter({ x is Circle }).map({ x.radius })
// error: Shape has no field radius on every member: narrow the value firstUse flatMap with is to get an Array[Circle]:
type Circle = { radius: float64 }
type Rect = { width: float64, height: float64 }
type Shape = Circle | Rect
let shapes: Array[Shape] = [Circle{ radius: 1.0 }, Rect{ width: 2.0, height: 3.0 }]
let circles: Array[Circle] = shapes.flatMap({ if x is Circle { [x] } else { [] } })
circles.map({ x.radius }) // [1.0]See also
Array.find, Array.countWhere, Array.every, Array.some, Array.map, Array.entries, Array.flatMap, Array.uniqueBy, Map.filter, Iter.filter
