Reference · Lists

filter

signature
filter(list | null, fn) -> list

What it does

The items for which the function gives a true value, in their original order, as a new list. The function takes one argument, the item. A result counts as true the way if reads it: only false and null drop the item; 0, "" and [] keep it. null counts as an empty list and gives [].

An error the function gives comes back as the result: it has said neither yes nor no, and a failed check must not look like nothing to see. So filter(xs, f)? stops there.

Examples

print(filter([1, 2, 3, 4], (x) => x % 2 == 0))let people = [{ name: "Ann", age: 30 }, { name: "Bo", age: 15 }]print(filter(people, (p) => p.age >= 18))print(filter(["a", "", "b"], (s) => s != ""))
output
[2, 4][{ name: "Ann", age: 30 }]["a", "b"]

Edge cases

print(filter([], (x) => true), filter(null, (x) => true))print(filter([1, 2], (x) => x > 5))print(filter([0, 1, "", "a", null, [], {}, false], (x) => x))print(filter([int("1"), int("x"), int("3")], (v) => !is_err(v)))let xs = [1, 2, 3]let evens = filter(xs, (x) => x % 2 == 0)print(xs, evens)
output
[] [][][0, 1, "", "a", [], {}][1, 3][1, 2, 3] [2]

Errors

A first argument that is not a list or null, or a second that is not a function, is a runtime error, not an error value. An error inside the function stops the request at the item that failed.

this one fails
print(filter({ a: 1 }, (x) => true))
output
line 1: `filter` expects a list as argument 1, got map
this one fails
print(filter([1, "a"], (x) => x > 0))
output
line 1: cannot compare str with int  in a function, called at main.qwe:1

Chaining

In a pipeline the list comes first: xs | filter(f). Pair it with map to change what is kept, count to only count the matches, find when one item is enough.

print([3, 1, 2, 5] | filter((x) => x > 1) | sort)print(split(",a,,b,", ",") | filter((p) => p != "") | join("-"))print(["7", "x", "9"] | map(int) | filter((v) => !is_err(v)))
output
[2, 3, 5]a-b[7, 9]

See also

map, find, count, any, all, unique

Thread
7Useful? Like it, or add to its thread below.

Thread 0 posts

On filter(): questions, tips, corrections, and code that uses it.

No posts yet. The first one opens the thread.

    Edit this page on GitHub · every example's output was made by running it (tools/refcheck.mjs) · questions on Discord or r/quillo