SyntaxStudy
Sign Up
JavaScript Intermediate 8 min read

flat() and flatMap()

Array flat() and flatMap()

Nested arrays — arrays containing other arrays — are common when grouping data, processing API responses, or generating results from a map. The flat() and flatMap() methods, introduced in ES2019, make working with nested arrays much simpler.

flat(depth)

flat() creates a new array with all sub-array elements concatenated into it up to the specified depth. The default depth is 1. Pass Infinity to flatten to any depth.

flatMap(fn)

flatMap(fn) is equivalent to calling .map(fn).flat(1) but more efficient because it combines both operations in a single pass. It is particularly useful when a mapping function needs to return zero, one, or multiple elements per input item.

Use Cases

  • Flattening paginated API results (array of arrays)
  • Splitting sentences into words and collecting all words
  • Expanding items with conditional duplication
Example
const nested = [1, [2, 3], [4, [5, 6]]];
console.log(nested.flat());        // [1,2,3,4,[5,6]]
console.log(nested.flat(2));       // [1,2,3,4,5,6]
console.log(nested.flat(Infinity));// [1,2,3,4,5,6]
const sentences = ['hello world', 'foo bar'];
const words = sentences.flatMap(s => s.split(' '));
console.log(words); // ['hello','world','foo','bar']
const nums = [1, 2, 3];
const result = nums.flatMap(n => n % 2 === 0 ? [] : [n, n * 10]);
console.log(result); // [1,10,3,30]
Pro Tip

Use flatMap to filter and transform in a single pass — return an empty array [] to drop an element, or a multi-element array to expand it, making it more expressive than a filter followed by a map.