Array.flat() & Array.flatMap()
TL;DR
Array.flat(depth) flattens nested arrays; Array.flatMap() maps then flattens one level — more efficient than map().flat() and great for expanding items.
Explanation
arr.flat() flattens one level by default. arr.flat(Infinity) flattens completely. arr.flat(2) flattens 2 levels. arr.flatMap(fn) is equivalent to arr.map(fn).flat(1) but more efficient. flatMap use cases: expanding one item into multiple (expanding tags into all tag instances), filtering and transforming (return [] to skip, return [item] or [a, b] to keep/expand). flat() replaces manual reduce-concat patterns. Both are ES2019 — use polyfills for IE11 (or Babel).
Common Misconception
✗ flatMap() flattens all levels — it only flattens one level. Use flat(Infinity) for deep flattening.
Why It Matters
flatMap() replaces the common but verbose reduce((acc, x) => [...acc, ...fn(x)], []) pattern with a clean, readable alternative.
Common Mistakes
- Using flatMap() expecting deep flattening — only one level.
- Not knowing flat() without arguments flattens only 1 level.
- Using reduce + concat instead of flat()/flatMap() — verbose and slow.
Code Examples
✗ Vulnerable
// Verbose reduce-concat:
const tags = posts.reduce((acc, post) => acc.concat(post.tags), []);
// Manual flat:
const nested = [[1,2],[3,4]];
const flat = [].concat(...nested);
✓ Fixed
const tags = posts.flatMap(post => post.tags);
// Filter + transform in one pass:
const active = items.flatMap(item =>
item.active ? [{ ...item, label: item.name.toUpperCase() }] : []
);
// Deep flatten:
const deep = nested.flat(Infinity);
References
Tags
🤝 Adopt this term
£79/year · your link shown here
Added
23 Mar 2026
Views
25
🤖 AI Guestbook educational data only
|
|
Last 30 days
Agents 0
No pings yet today
No pings yesterday
Amazonbot 8
Perplexity 5
Unknown AI 4
ChatGPT 1
Majestic 1
Google 1
Ahrefs 1
Also referenced
How they use it
crawler 18
pre-tracking 3
Related categories
⚡
DEV INTEL
Tools & Severity
🔵 Info
⚙ Fix effort: Low
⚡ Quick Fix
Replace reduce-concat patterns with flatMap(). Replace [].concat(...arr) with arr.flat(). Use flatMap(x => condition ? [x] : []) for filter+transform.
📦 Applies To
javascript ES2019
web
cli
🔗 Prerequisites
🔍 Detection Hints
reduce.*concat|\[\]\.concat
Auto-detectable:
✓ Yes
eslint
🤖 AI Agent
Confidence: Medium
False Positives: Medium
✓ Auto-fixable
Fix: Low
Context: Line