liveBook · Manning

Flat

As explained in Secrets of the JavaScript Ninja, Third Edition

The flat method creates an array by replacing nested arrays with their elements to a specified depth.

Need to turn nested arrays into one array? JavaScript’s `flat` replaces nested arrays with their elements. It flattens one level by default; pass a depth to flatten more levels. section 10.1.4

Depth matters

`[[1], [2, [3]]].flat()` produces `[1, 2, [3]]`. The `[3]` remains nested because it was two levels deep. section 10.1.4

Pair `map` with `flat` when one input item should produce several output items—or none. For that one-to-many transformation, `flatMap` combines the two steps in one operation. section 10.1.4

How Secrets of the JavaScript Ninja, Third Edition covers it

How deep it goes
Defines default and optional flattening depth with one worked expression; stops short of implementation internals.
Examples
Shows a nested-number array flattened one level and an array of weapon lists combined with flatMap.
What it assumes
Assumes familiarity with arrays and mapping callbacks while defining flattening directly.
What you can do after
Apply it via JavaScript’s flat method to choose how many levels of nested arrays to flatten.
How it connects
Connects flat to map and flatMap for one-to-many array transformations.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Secrets of the JavaScript Ninja, Third Edition. The section links point to the parts of the book it draws on.