flatMap Flattens One Element Level

flatMap maps and flattens exactly one array level, so triple-nested arrays stay partially nested and branches must return arrays for a consistent element type.

TypescriptData Integrity

Code

typescriptsnippet
21 lines
// flatMap maps and flattens exactly ONE element level, and the types agree.
const rows: number[][] = [[1, 2], [], [3, 4]];
const numbers: number[] = rows.flatMap((row) => row);
console.log('one level:', numbers);

// Triple-nested arrays lose only one layer per call
const deep: number[][][] = [[[1, 2]], [[3]]];
const once: number[][] = deep.flatMap((group) => group);
console.log('still nested:', JSON.stringify(once));

// Branches return arrays, so the element type U stays consistent
const labels: string[] = rows.flatMap((row) =>
  row.length === 0 ? ['empty row'] : row.map((n) => String(n)),
);
console.log('labels:', labels);

// Map-and-skip in one pass: return [] to drop an element
const kept: string[] = ['a', '', 'b'].flatMap((value) =>
  value ? [value.toUpperCase()] : [],
);
console.log('kept:', kept);

Output

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

one level: [ 1, 2, 3, 4 ]
still nested: [[1,2],[3]]
labels: [ '1', '2', 'empty row', '3', '4' ]
kept: [ 'A', 'B' ]

Putting it to use

The demo output is labeled (one level:, still nested:, labels:), so every line of output points back to the operation that emitted it.

Output is labeled for readability — expect lines prefixed with one level:, still nested:, labels:.

The core lines of the flow

const once: number[][] = deep.flatMap((group) => group);
const numbers: number[] = rows.flatMap((row) => row);
const kept: string[] = ['a', '', 'b'].flatMap((value) =>
  value ? [value.toUpperCase()] : [],
);

Interactive Tools for This Topic

FAQ

Can I paste this into a project as-is?
Yes. Paste it in and run; no package manager step is needed.