flatMap Flattens Nested Result Pages
Replace map-then-flatten chains with flatMap: each page contributes its items array in one callback and a single pass yields one flat result list.
Code
// 每页是 { items: [] }:flatMap 一次完成“取字段 + 压平”两步
const pages = [
{ page: 1, items: ['alpha.log', 'beta.log'] },
{ page: 2, items: [] },
{ page: 3, items: ['gamma.log'] },
];
const files = pages.flatMap((p) => p.items);
console.log(files.join(', '));
// 映射结果也支持展开:每条记录拆成带页码的形式
const indexed = pages.flatMap((p) => p.items.map((name) => `${name}#p${p.page}`));
console.log(indexed.join(', '));
// 对照:flat 只压平已有嵌套,flatMap 先映射再压平
const matrix = [
[1, 2],
[3, 4],
];
console.log(matrix.flat().join(' + '), '=', matrix.flat().reduce((a, b) => a + b, 0));Output
Captured from a sandboxed run of this snippet in the build pipeline.
alpha.log, beta.log, gamma.log
alpha.log#p1, beta.log#p1, gamma.log#p3
1 + 2 + 3 + 4 = 10How it works
Everything operates on top-level bindings: pages, files, indexed, matrix.
Each entry in pages carries an items array, and pages.flatMap((p) => p.items) concatenates them in a single pass — the empty page 2 simply contributes nothing. The second flatMap maps each item to a page-tagged name such as alpha.log#p1 before flattening, so the suffix travels with its source page. The trailing matrix.flat() contrast shows that flat only flattens existing nesting, while flatMap maps and flattens in one call.
Core lines
const indexed = pages.flatMap((p) => p.items.map((name) => `${name}#p${p.page}`));
const files = pages.flatMap((p) => p.items);
FAQ
- Any setup needed beyond the language runtime?
- None — the language runtime is the only requirement. Its state lives in module-level bindings: `pages`, `files`, `indexed`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.