Sub topic 15
Flattening Nested Arrays with flat and flatMap
This chapter assumes you already know map and the (element, index, array) callback signature. It also assumes you know the difference between methods that mutate an array and methods that return a new one.
Nested arrays show up often. API responses group items by category, split returns an array for each string, and lookups return a list for each key. flat and flatMap turn that nested structure into a single-level array. Neither method changes the original array.
How flat works
flat(depth) returns a new array in which nested arrays are merged into their parent, up to depth levels. The default depth is 1.
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 takes away one pair of brackets. If you don't know how deep the data goes, Infinity flattens it completely.
flat also drops empty slots in sparse arrays. That can be convenient, but it means the result may be shorter than you expect:
console.log([1, , 3, [4, , 6]].flat()); // [1, 3, 4, 6]How flatMap works
flatMap(callback) gives the same result as map(callback).flat(), but it does it in a single pass. The callback receives the usual (element, index, array) arguments.
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']Using flatMap to filter and expand
The callback can return an array of any length, so flatMap can map and filter in the same step:
- Return
[]to drop the element. - Return
[x]to keep exactly one value. - Return
[x, y]to produce more than one value.
const items = [
{ name: 'pen', qty: 2 },
{ name: 'ink', qty: 0 },
{ name: 'pad', qty: 1 }
];
const labels = items.flatMap(item =>
item.qty === 0 ? [] : Array(item.qty).fill(item.name)
);
console.log(labels); // ['pen', 'pen', 'pad']Common mistakes
| Mistake | What happens | Fix |
|---|---|---|
| Expecting `flat()` to flatten everything | Only one level is removed | Pass a depth, or use `Infinity` |
| Expecting `flatMap` to flatten deeply | It always flattens exactly one level | Use `map(...).flat(depth)` |
| Returning a non-array from `flatMap` | The value is kept as it is, which is fine but easy to misread | Return arrays consistently |
| Assuming the length is preserved | Empty slots are removed | Check for sparse input |
Exercise
Given const tags = [['js', 'web'], ['node'], [], ['js']]; write one expression that produces a flat array of unique tags.
Show answer
[...new Set(tags.flat())] returns ['js', 'web', 'node']. flat() merges the inner arrays into ['js', 'web', 'node', 'js'], the Set removes the duplicate, and spread syntax turns the Set back into an array.
Exercise
What does [1, 2, 3].flatMap(n => n % 2 ? [n, n * 10] : []) return, and why?
Show answer
[1, 10, 3, 30]. Odd numbers return a two-element array, so each one expands to two values. The even number 2 returns [], so it is dropped. flatMap then merges the results one level deep.