Normalize nested data
A collection contains arrays nested one or more levels deep and needs a new, shallower array.
JS Puzzles · Const
Use flat() to create a new array with nested arrays concatenated to a chosen depth. Use flatMap() when transforming elements and flattening the results by one level in one operation.
JavaScript provides flat() for depth-controlled flattening and flatMap() for mapping each element followed by one-level flattening. Both return new arrays rather than modifying the original array.
array.flat(depth)
array.flatMap(callbackFn, thisArg)| Name | Type | Description |
|---|---|---|
depth | number | Maximum nesting depth to flatten; defaults to 1. A larger value allows deeper nested arrays to be concatenated. |
callbackFn | function | Function called for each present array element; its returned arrays are flattened one level. |
thisArg | any | Optional value used as this when callbackFn executes. |
flat() returns a new array with nested array elements concatenated through the requested depth. flatMap() returns a new array containing callback results flattened by one level.
const nested = [1, [2, [3, 4]], 5];
const oneLevel = nested.flat();
const completelyFlat = nested.flat(Infinity);
const expanded = [1, 2, 3].flatMap((n) => [n, n * 10]);
console.log(oneLevel); // [1, 2, [3, 4], 5]
console.log(completelyFlat); // [1, 2, 3, 4, 5]
console.log(expanded); // [1, 10, 2, 20, 3, 30]Use flat() to copy an array while concatenating nested arrays to a chosen depth; use flatMap() when mapping and flattening one level belong together.
A collection contains arrays nested one or more levels deep and needs a new, shallower array.
Each input element should produce zero, one, or several output elements.
A legacy reduce-and-concat flattening expression should be replaced by the built-in operation.
flat() returns a new array and concatenates nested arrays recursively up to the supplied depth. With no argument, the depth is 1.
Follow-up: What happens with deeper nesting? Call flat() with a larger depth, such as Infinity, to continue through all nested levels.
flatMap() applies a callback to each present element and then flattens the callback results by exactly one level. It combines the usual map(...).flat(1) operation.
Follow-up: Can the callback return a scalar? Yes; only returned arrays are flattened, while scalar results become ordinary elements.
Neither method mutates the receiver. flat() produces a shallow copied result, while flatMap() creates a new array containing mapped results flattened one level.
Follow-up: What does flat() do to sparse arrays? It removes empty slots at the levels being flattened.
Array.prototype.map()Array.prototype.flat()Array.prototype.flatMap()Array.prototype.reduce()Array.isArray()