flat() & flatMap() in JavaScript
From the JavaScript Array Methods cheat sheet · Iteration Methods · verified Jul 2026
flat() & flatMap()
Flatten nested arrays and map-then-flatten
javascript
// Flatten nested arrays
[1, [2, 3]].flat(); // [1, 2, 3]
[1, [2, [3]]].flat(2); // [1, 2, 3] (depth 2)
// Map and flatten
[1, 2].flatMap(x => [x, x * 2]); // [1, 2, 2, 4]
// Remove empty slots
[1, , 3].flat(); // [1, 3]💡 flat() removes nesting levels (default: 1)
⚡ flatMap() = map() + flat(1) in one pass
📌 Use Infinity to flatten all levels
🔗 Great for handling nested data structures
⚠️ Removes empty slots from arrays