Codectionary / Developer documentation / JavaScript

flat() and flatMap()

flat() creates a new array with nested sub-arrays flattened up to a specified depth (default 1 level). flatMap() combines mapping and flattening in a single, more efficient step - it maps each element and then flattens the result by exactly one level, useful when a mapping function returns an array for each item.

Syntax

arr.flat(depth)
arr.flatMap(item => [values])

Examples

flat() - Flattening Nested Arrays

Flattening arrays to different depths.

const nested = [1, [2, 3], [4, [5, 6]]];

console.log(nested.flat());     // [1, 2, 3, 4, [5, 6]] - only 1 level by default
console.log(nested.flat(2));    // [1, 2, 3, 4, 5, 6] - 2 levels deep
console.log(nested.flat(Infinity)); // fully flattens any depth

flatMap() - Map Then Flatten

A common use case: expanding each element into multiple elements.

const sentences = ["Hello world", "How are you"];

const words = sentences.flatMap(s => s.split(" "));
console.log(words); // ["Hello", "world", "How", "are", "you"]

// Equivalent to, but more efficient than:
// sentences.map(s => s.split(" ")).flat()

Best practices

  • Use flat() when you already have a nested array structure that needs flattening
  • Use flatMap() instead of .map().flat() when your mapping function returns arrays - it is more efficient since it avoids creating an intermediate array
  • Be cautious with flat(Infinity) on deeply nested or very large structures - consider whether the nesting itself should be avoided at the source
  • Remember flat() and flatMap() both return new arrays and do not modify the original

At a glance

Purpose
Application logic and interaction
File extension
.js ยท .mjs
Runs in
Browsers and JavaScript runtimes
Usually used with
HTML, CSS and Web APIs

Specifications & further reading

Related JavaScript documentation