Array flat() and flatMap()
The flat() method of Array instances creates a new array with all sub-array elements concatenated into it recursively up to the specified depth.
Browser support
| Feature | Desktop | Mobile | ||||
|---|---|---|---|---|---|---|
| Chrome | Edge | Firefox | Safari | Chrome Android | Safari iOS | |
| 69 | 79 | 62 | 12 | 69 | 12 | |
| Built-in object | ||||||
| The flatMap() method of Array instances returns a new array formed by applying a given callback function to each element of the array, and then flattening the result by one level. It is identical to a Array/map followed by a Array/flat of depth 1 (arr.map(...args).flat()), but slightly more efficient than calling those two methods separately. | 69 | 79 | 62 | 12 | 69 | 12 |
Syntax
const nested = [1, [2, 3], [4, [5, 6]]];
nested.flat(); // [1, 2, 3, 4, [5, 6]]
nested.flat(2); // [1, 2, 3, 4, 5, 6]
nested.flat(Infinity); // Flattens everything
// flatMap: One-to-many transformation
const sentences = ['Hello World', 'Good Morning'];
sentences.flatMap(s => s.split(' '));
// ['Hello', 'World', 'Good', 'Morning'] Live demo
Flatten nested arrays
Compare flat(), flat(2), and flat(Infinity) on the same nested input.
Split sentences with flatMap
Map each sentence to multiple words and flatten the combined result in one step.
Use cases
-
Flattening nested data
Turn grouped arrays into a simple list before filtering, rendering, or exporting data.
-
Map and flatten together
Use flatMap when one item becomes zero, one, or many items and you want one readable pipeline.
Cautions
- flat() creates a new array, so very large nested structures still have a memory cost.
- flatMap() only flattens one level; use flat() afterward if deeper nesting is expected.
Accessibility
- Flattened arrays often drive rendered lists, so keep DOM order meaningful when you transform grouped content into one sequence.