flat Flattens Nested Arrays By Depth

flat() unwraps one level by default, a depth argument digs deeper, sparse holes disappear, and flatMap is just map followed by flat(1).

JavascriptData Integrity

Code

javascriptsnippet
18 lines
const nested = [1, [2, 3], [4, [5, 6]]];

// flat(depth):默认只展开一层
console.log("flat()        :", nested.flat());
console.log("flat(2)       :", nested.flat(2));
console.log("flat(Infinity):", nested.flat(Infinity));

// flatMap = map 之后接 flat(1):一项拆多项时常用
const words = ["ab", "cd"];
console.log("flatMap       :", words.flatMap((word) => word.split("")));

// 稀疏位(empty slot)会被 flat 顺手移除
const withHoles = [1, , 3];
console.log("holes         :", withHoles.flat());

// 多层树形结构:flat(Infinity) 一次压平所有层
const tree = [[1, [2]], [3, [4, [5]]]];
console.log("tree          :", tree.flat(Infinity));

Output

Captured from a sandboxed run of this snippet in the build pipeline.

flat()        : [ 1, 2, 3, 4, [ 5, 6 ] ]
flat(2)       : [ 1, 2, 3, 4, 5, 6 ]
flat(Infinity): [ 1, 2, 3, 4, 5, 6 ]
flatMap       : [ 'a', 'b', 'c', 'd' ]
holes         : [ 1, 3 ]
tree          : [ 1, 2, 3, 4, 5 ]

How the snippet works

Top-level bindings nested, words, withHoles, tree hold the demo state — nothing sits inside a function scope.

Applying it

The demo output is labeled (flat(Infinity):), so every printed line maps back to its originating operation.

Statements that matter

const nested = [1, [2, 3], [4, [5, 6]]];
const tree = [[1, [2]], [3, [4, [5]]]];
const words = ["ab", "cd"];

Interactive Tools for This Topic

FAQ

Are there any imports to resolve outside the language?
No. Every import resolves against the language's own modules. Its state lives in module-level bindings: `nested`, `words`, `withHoles`.