Flattening
You may have heard of a “flatten” function. Flatten functions take an input of some sort and “unwrap” it. (In this case, unwrapping an array is to pull out the elements in the array and use those.) This hypothetical code snippet returns [2, 4, 7, 12]:
| | flatten([[2], [4, 7], 12]) |
Usually, a single call to flatten only unwraps by one layer. Flatten iterates through the array, unwrapping each item if possible. The element 12 cannot be unwrapped, so flatten uses the raw value in the resulting collection. Flatten can be used with more than arrays—promises and observables also can be unwrapped by passing along the data within rather than the abstraction. Promise.all is a type of flatten, taking an array of promises and returning a single ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access