JavaScript flat() and flatMap(): Flatten One or More Levels
Quick answer
flat() concatenates nested arrays up to a selected depth. flatMap() maps present elements and flattens array results one level.
How it works
flat(depth = 1) removes ordinary holes at traversed levels; depth 0 still copies present top-level elements. Only actual arrays are flattened, not arbitrary array-like objects. flatMap(callback) allows zero, one or many results by returning arrays; scalar results are appended unchanged. The examples use JSON.stringify as a preview of serialization to display nested arrays compactly; JSON is covered later.
const a = [1, [2, [3]]];console.log(JSON.stringify(a.flat()), JSON.stringify(a.flat(2)));Expected output in Node.js:
[1,2,[3]] [1,2,3]The chosen depth controls how many nested levels are removed.
console.log([2, 0, 3].flatMap(n => n === 0 ? [] : [n,n*2]).join(","));Expected output in Node.js:
2,4,3,6An empty returned array contributes no elements.
Common mistakes
FlatMap always flattens one level, not arbitrary depth. Avoid assuming flat is a deep clone.
Practice
Expand each nonzero score into a pair and drop zero scores with flatMap.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
JavaScript flat() and flatMap(): Flatten One or More Levels — Knowledge Check
Apply the taught concept and predict the output.
What is the default depth of flat?
Which callback result allows flatMap to omit an element entirely?
Does flatMap flatten an ordinary object with a length property?
What is the exact console output in JavaScript flat() and flatMap(): Flatten One or More Levels example 1?
const a = [1, [2, [3]]];console.log(JSON.stringify(a.flat()), JSON.stringify(a.flat(2)));What is the exact console output in JavaScript flat() and flatMap(): Flatten One or More Levels example 2?
console.log([2, 0, 3].flatMap(n => n === 0 ? [] : [n,n*2]).join(","));