Reference · Lists
filter
filter(list | null, fn) -> listWhat 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 != ""))[2, 4][{ name: "Ann", age: 30 }]["a", "b"]Edge cases
- An empty list or
nullgives[]. - Nothing matching gives
[], nevernull. - The function's result is read for truth, not compared with
true: returning the item itself drops onlynullandfalse, and keeps0and"". To leave out errors, ask:filter(xs, (x) => !is_err(x)). Error values are falsy, sofilter(xs, (v) => v)is one way to keep the good results of a conversion. - The list given is not changed;
filterbuilds a new one.
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)[] [][][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.
print(filter({ a: 1 }, (x) => true))line 1: `filter` expects a list as argument 1, got mapprint(filter([1, "a"], (x) => x > 0))line 1: cannot compare str with int in a function, called at main.qwe:1Chaining
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)))[2, 3, 5]a-b[7, 9]See also
map, find, count, any, all, unique
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