JavaScript flat() and flatMap() - Flatten Nested Arrays
Learn Array.flat() and flatMap() for flattening nested arrays. Covers depth control, one-to-many mappings, and combined filter+map patterns. Free reference.
Detailed Explanation
Understanding flat() and flatMap()
Array.flat()
flat() creates a new array with sub-arrays concatenated recursively up to a specified depth.
const nested = [1, [2, 3], [4, [5, 6]]];
nested.flat(); // [1, 2, 3, 4, [5, 6]] (depth 1)
nested.flat(2); // [1, 2, 3, 4, 5, 6] (depth 2)
nested.flat(Infinity); // [1, 2, 3, 4, 5, 6] (all levels)
flat() also removes empty slots from sparse arrays:
[1, , 3, , 5].flat(); // [1, 3, 5]
Array.flatMap()
flatMap() maps each element then flattens the result by one level. It is equivalent to map().flat(1) but more efficient.
const sentences = ["hello world", "foo bar baz"];
const words = sentences.flatMap(s => s.split(" "));
// words: ["hello", "world", "foo", "bar", "baz"]
flatMap for Filter + Map
flatMap can combine filtering and mapping in a single pass:
const nums = [1, 2, 3, 4, 5, 6];
// Keep even numbers and double them
const result = nums.flatMap(n => n % 2 === 0 ? [n * 2] : []);
// result: [4, 8, 12]
Return [] to exclude an element, [value] to include it, or [a, b] to expand it into multiple elements.
One-to-Many Mappings
flatMap excels at expanding each element into multiple:
const users = [
{ name: "Alice", pets: ["cat", "dog"] },
{ name: "Bob", pets: ["fish"] }
];
const allPets = users.flatMap(u => u.pets);
// allPets: ["cat", "dog", "fish"]
Performance Considerations
flatMap()is ~2x faster thanmap().flat()because it avoids creating the intermediate arrayflat(Infinity)on deeply nested structures can be slow; specify the exact depth when known- For very large arrays, consider iterative approaches
Use Case
Use flat() when working with nested API responses (like tree structures) or merging arrays of arrays. Use flatMap() for one-to-many transformations like splitting strings, expanding nested properties, or combined filter+map operations.