freecoding.school100% FREE · NO SIGNUP
Closure CavesISSUE #24 of 61

array methods · flat · flatMap

LambdaVSThe Mutator
Lambda saysflat flattens nested arrays; flatMap maps then flattens one level.

[1, [2, [3]]].flat() flattens one level (pass a depth, or Infinity, for deeper). flatMap(fn) is map followed by a one-level flat — handy when each item expands into several (e.g. splitting words from lines) without a separate flatten step.

Power-ups you unlock

The Mutator attacks — common mistakes

Boss battleUse flatMap to split each sentence into words across an array of sentences.

Example code

<!doctype html><html><head><meta charset="utf-8"></head>
<body style="background:#06040d;color:#e6e0ff;font-family:monospace;padding:20px"><pre id="o"></pre>
<script>const lines=['a b','c d']; const words=lines.flatMap(l=>l.split(' '));
document.getElementById('o').textContent=words.join(',');</script></body></html>
▶ Open the interactive comic issue
‹ Array Methods · Sort · ReverseArray-Like Vs Array ›