What is the difference between flat() and flatMap()?
Short 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.
Advertisement
AModel 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.
Likely follow-ups
- How would you fully flatten a deeply nested array of unknown depth?
Related topics