← CodeClarityLab Home
Browse by Category
+ added · updated 7d
← Back to glossary

Array.flat() & Array.flatMap()

javascript ES2019 Beginner

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);

Added 23 Mar 2026
Views 25
Rate this term
No ratings yet
🤖 AI Guestbook educational data only
| |
Last 30 days
0 pings W 0 pings T 1 ping F 2 pings S 0 pings S 0 pings M 0 pings T 0 pings W 0 pings T 1 ping F 0 pings S 0 pings S 0 pings M 0 pings T 0 pings W 0 pings T 1 ping F 1 ping S 0 pings S 0 pings M 0 pings T 0 pings W 1 ping T 1 ping F 0 pings S 0 pings S 0 pings M 0 pings T 0 pings W 0 pings T
No pings yet today
No pings yesterday
Amazonbot 8 Perplexity 5 Unknown AI 4 ChatGPT 1 Majestic 1 Google 1 Ahrefs 1
crawler 18 pre-tracking 3
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

✓ schema.org compliant