Sub topic 15
Flattening Nested Arrays with flat and flatMap
Nested arrays appear all the time. You might get rows of a grid, the tags of several posts, or the results of an API call that returns lists inside lists. Two methods turn that structure into a single list. flat removes nesting levels, and flatMap transforms each element and then removes one level.
This chapter assumes you already know how map and its (element, index, array) callback signature work, and that you can tell a method that mutates its array from one that returns a new one. Both methods were added in ES2019 and work in all current browsers and Node.js 11 and later.
What flat Does
flat(depth) returns a new array. Any element that is itself an array gets its contents pulled up into the parent, and this repeats up to depth levels. The default depth is 1. The original array is never changed.
const nested = [1, [2, [3, [4]]]];
console.log(nested.flat()); // [1, 2, [3, [4]]]
console.log(nested.flat(2)); // [1, 2, 3, [4]]
console.log(nested.flat(Infinity)); // [1, 2, 3, 4]
console.log(nested); // [1, [2, [3, [4]]]] (unchanged)Each level of depth removes one layer of brackets. Infinity keeps going until no arrays are left, which is useful when you don't know how deep the data goes.
How depth is interpreted
The engine converts the argument to an integer. Some values behave in ways you might not expect:
| Call | Effective depth | Result for `[1, [2, [3]]]` |
|---|---|---|
| `flat()` | 1 | `[1, 2, [3]]` |
| `flat(0)` | 0 | `[1, [2, [3]]]` (shallow copy) |
| `flat(-1)` | 0 | `[1, [2, [3]]]` |
| `flat(1.9)` | 1 (truncated) | `[1, 2, [3]]` |
| `flat('2')` | 2 | `[1, 2, 3]` |
| `flat(NaN)` | 0 | `[1, [2, [3]]]` |
Negative numbers and NaN don't throw. They quietly act like 0. If a computed depth seems to be ignored, log it before the call.
Only real arrays are flattened
flat checks whether each element is a genuine array, which is the same test Array.isArray performs. Strings, array-like objects, Sets, and other iterables stay as single elements.
const mixed = [[1, 2], 'ab', new Set([3, 4]), { 0: 'x', length: 1 }];
console.log(mixed.flat());
// [1, 2, 'ab', Set(2) {3, 4}, { '0': 'x', length: 1 }]To flatten a Set or an array-like object, convert it with Array.from or spread syntax first.
const groups = [new Set([1, 2]), new Set([2, 3])];
const all = groups.map(s => [...s]).flat();
console.log(all); // [1, 2, 2, 3]flat Removes Holes
A sparse array has empty slots. These are positions that were never assigned, which is different from positions that hold undefined. flat skips empty slots at every level it visits, including the top level, even when the depth is 0.
const sparse = [1, , 3, [4, , 6]];
console.log(sparse.flat()); // [1, 3, 4, 6]
console.log(sparse.flat(0)); // [1, 3, [4, , 6]]
const withUndefined = [1, undefined, 3];
console.log(withUndefined.flat()); // [1, undefined, 3]Look at the flat(0) result. The top-level hole is gone, but the hole inside the nested array is still there, because depth 0 never opens that inner array.
What flatMap Does
flatMap(callback) calls the callback on every element, exactly as map does, and then flattens the result by one level. Its result matches arr.map(callback).flat(1), but it skips building the intermediate array.
const sentences = ['hello world', 'hi'];
console.log(sentences.map(s => s.split(' ')));
// [['hello', 'world'], ['hi']]
console.log(sentences.flatMap(s => s.split(' ')));
// ['hello', 'world', 'hi']The callback receives (element, index, array), and an optional second argument to flatMap sets this inside a regular function callback. This works the same way as map.
Returning zero, one, or many elements
flatMap is more flexible than map because each input element can produce any number of output elements:
- Return
[]to drop the element. - Return a single value (or
[value]) to keep one element. - Return
[a, b, c]to produce several elements.
That lets you filter and transform in a single pass:
const lines = [' apple ', '', 'banana', ' ', 'cherry'];
const cleaned = lines.flatMap(line => {
const trimmed = line.trim();
return trimmed ? [trimmed.toUpperCase()] : [];
});
console.log(cleaned); // ['APPLE', 'BANANA', 'CHERRY']It can also expand data, for example by turning each order into one row per item:
const orders = [
{ id: 1, items: ['pen', 'ink'] },
{ id: 2, items: [] },
{ id: 3, items: ['pad'] }
];
const rows = orders.flatMap(order =>
order.items.map(item => ({ orderId: order.id, item }))
);
console.log(rows);
// [
// { orderId: 1, item: 'pen' },
// { orderId: 1, item: 'ink' },
// { orderId: 3, item: 'pad' }
// ]Order 2 has no items, so it produces nothing. You don't need a separate filter step.
flatMap flattens exactly one level
The depth of flatMap is fixed at 1 and cannot be changed. If your callback returns nested arrays, the inner layers survive.
console.log([1, 2].flatMap(x => [[x, x * 10]]));
// [[1, 10], [2, 20]]
console.log([1, 2].map(x => [[x, x * 10]]).flat(2));
// [1, 10, 2, 20]When you need a deeper flatten, use map followed by flat(n).
Gotchas and Failure Modes
Cyclic arrays and flat(Infinity)
If an array contains itself, directly or through another array, flat(Infinity) recurses without end and throws a RangeError once the call stack runs out.
const loop = [1];
loop.push(loop);
try {
loop.flat(Infinity);
} catch (err) {
console.log(err instanceof RangeError); // true
}A finite depth such as flat(3) is safe even with cycles, because it stops after three levels. Very deep acyclic nesting can also overflow the stack, but you would need thousands of levels for that to happen.
Shallow results
Flattening copies references. It does not copy the objects themselves. Changing an object inside the flattened array also changes it in the original structure.
const source = [[{ n: 1 }]];
const flatList = source.flat();
flatList[0].n = 99;
console.log(source[0][0].n); // 99Choosing between them
| Situation | Use |
|---|---|
| Data is already nested and you only need to remove levels | `flat(n)` |
| Unknown nesting depth, no cycles possible | `flat(Infinity)` |
| Each element maps to zero or more outputs | `flatMap` |
| Transform and flatten more than one level | `map(...).flat(n)` |
| Flatten Sets, strings, or array-likes | Convert with `Array.from` first |
Exercise
What does [[1, [2]], , [3]].flat() return, and why is there no hole in the result?
Show answer
It returns [1, [2], 3]. Depth 1 opens the arrays [1, [2]] and [3] but leaves [2] nested. The empty slot at index 1 is skipped because flat drops holes at every level it visits.
Exercise
Use flatMap to turn [1, 2, 3, 4] into an array that drops odd numbers and repeats each even number twice, giving [2, 2, 4, 4].
Show answer
[1, 2, 3, 4].flatMap(n => n % 2 === 0 ? [n, n] : []). An odd number returns an empty array, which disappears after flattening. An even number returns a two-element array, which becomes two elements.
Exercise
A colleague writes data.flatMap(x => x) to fully flatten data = [1, [2, [3]]]. What do they get, and what should they write instead?
Show answer
They get [1, 2, [3]], because flatMap flattens only one level. To flatten fully they should write data.flat(Infinity), as long as data cannot contain a reference to itself.