Skip to content

flat() and flatMap()

flat() creates a new array with all sub-array elements concatenated up to a specified depth. flatMap() maps then flattens in one step.

[1, [2, [3]]].flat(); // [1, 2, [3]] — default depth: 1
[1, [2, [3]]].flat(2); // [1, 2, 3]
[1, [2, [3]]].flat(Infinity); // [1, 2, 3]
['hello world', 'foo bar'].flatMap(str => str.split(' '));
// ['hello', 'world', 'foo', 'bar']
// Equivalent to: arr.map(...).flat()
  • flat(depth) flattens nested arrays
  • flatMap() combines map + flat(1)
  • More efficient than separate map then flat