SyntaxStudy
Sign Up
Home JavaScript Reference flat() / flatMap()

flat() / flatMap()

method ES2019

flat() flattens nested arrays; flatMap() maps then flattens one level.

Syntax

array.flat(depth) array.flatMap(callback)

Example

javascript
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)); // fully flattened

const sentences = ['Hello World', 'Foo Bar'];
const words = sentences.flatMap(s => s.split(' '));
console.log(words); // ['Hello', 'World', 'Foo', 'Bar']