Reference · Lists

flatten

signature
flatten(list | null) -> list

What it does

One list from a list of lists: the items of each inner list, in order, one level deep. An item that is not a list is kept as it is. null counts as an empty list.

Examples

print(flatten([[1, 2], [3], []]))let teams = [{ members: ["ann", "bob"] }, { members: ["cy"] }]print(flatten(map(teams, (t) => t.members)))print(flatten([[1, [2, 3]], 4, "a"]))
output
[1, 2, 3]["ann", "bob", "cy"][1, [2, 3], 4, "a"]

Edge cases

print(flatten([]), flatten([[], []]), flatten(null))print(flatten([[[1]], [[2]]]), flatten([[[1]], [[2]]]) | flatten)print(flatten([1, null, [2]]))
output
[] [] [][[1], [2]] [1, 2][1, null, 2]

Errors

An argument that is not a list or null is a runtime error, not an error value.

this one fails
print(flatten("ab"))
output
line 1: `flatten` expects a list as argument 1, got str

Chaining

In a pipeline flatten takes the list and needs no arguments. After a map that gives a list per item it is a flat map.

print([[1, 2], [3]] | flatten | sum)print(["a b", "c"] | map((s) => split(s, " ")) | flatten)print(range(3) | map((i) => [i, i]) | flatten)
output
6["a", "b", "c"][0, 0, 1, 1, 2, 2]

See also

map, zip, push, join

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

Thread 0 posts

On flatten(): 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