Arrays
flat() and flatMap()
"Flattens" nested arrays into one.
Why it exists
Arrays of arrays turn up all the time: data arrived page by page, each article has its own list of tags, map returned an array for every item. One shared list is easier to show or process. flat does it in one call instead of a loop with spread.
Where it's used
- Paginated API responses:
pages.flat(). - Every tag of every article:
posts.flatMap((post) => post.tags). - Items from several warehouses or categories in one list.
Syntax
array.flat() // one level
array.flat(depth)
array.flatMap((item) => array)Examples
[[1, 2], [3, 4]].flat(); // → [1, 2, 3, 4][1, [2, [3, [4]]]].flat(); // → [1, 2, [3, [4]]]
[1, [2, [3, [4]]]].flat(Infinity); // → [1, 2, 3, 4]const posts = [{ tags: ["js", "css"] }, { tags: ["js"] }];
posts.flatMap((post) => post.tags); // → ["js", "css", "js"][1, 2, 3].flatMap((n) => (n % 2 ? [n, n] : [])); // → [1, 1, 3, 3]flatMap can both multiply and drop itemsResults after // → aren't just written down — an automatic check runs and verifies them before every site update.
Why it works this way
flat(depth) creates a new array: every item that is itself an array is replaced by its items. The default depth is 1: only the first level opens, and deeper arrays stay arrays. flat(Infinity) opens everything.
Along the way, flat skips "holes" in sparse arrays.
flatMap(fn) calls fn on each item, like map, and then flattens the result by one level. Handy when each item yields several values (or none — then the callback returns [] and the item simply disappears).
Traps
How it differs from…
- Spread
... result.push(...group)in a loop does whatflat()does, by hand — useful for understanding the mechanics.array.map()flatMapis map whose result is then flattened by one level.
When to pick something else
If the structure is deep and uneven (a comment tree with replies), flat(Infinity) loses the nesting information you most likely need. Trees like that are walked recursively.