Back to results for “Arrays & Array Methods”
JavaScript › Arrays & Array Methods

What is the difference between flat() and flatMap()?

Advanced

Answer

flat(depth) flattens nested arrays up to the given depth (default 1). flatMap() maps each element first, then flattens the result by one level — equivalent to map().flat() but computed in a single, more efficient pass.
[[1,2],[3,4]].flat(); // [1,2,3,4]
[1,2,3].flatMap(n => [n, n*2]); // [1,2,2,4,3,6]
Real-world example flatMap() to turn each order into multiple line-item records in one pass.

Common follow-ups: How would you fully flatten a deeply nested array of unknown depth?