Ad space (banner)
๐ŸŸฃJulia Lessons
Lesson 42 / 68

Flattening an array

This lesson covers flattening a nested array in Julia, with the aim of handling complicated structures simply.

When an array contains further arrays, expanding it into one flat array is called flattening. In Julia you do it with Iterators.flatten().

The sample code expands the nested [[1, 2], [3, 4], [5]] into [1, 2, 3, 4, 5] with collect(Iterators.flatten(nested)). Note that collect() turns the lazy iterator returned by Iterators.flatten() into an actual array.

A common early stumble is exactly that need for collect(). Iterators.flatten() alone leaves you with an iterator, and using it as an array means converting explicitly.

In professional work, this is a genuinely useful technique whenever nested data has to be handled as one flat list.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Julia directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)