What is flat()?

flat(depth = 1) returns a new array with nested arrays flattened into it up to the given depth; flat(Infinity) flattens completely, and flatMap maps and flattens one level in a single step.

Behaviour

  • Default depth is 1: only one level of nesting is removed.
  • flat(2), flat(3)... for deeper levels; flat(Infinity) for any depth.
  • Empty slots are removed from sparse arrays.
  • Returns a new array; the original is untouched.
  • Only arrays are flattened; other iterables (Sets, strings) stay as single elements.

flatMap

arr.flatMap(fn) is the same as arr.map(fn).flat() but more efficient. It is very handy when each item should produce zero, one or many results:

  • Return [] to drop an item (filter and map in one pass).
  • Return [a, b] to expand one item into several.

Use cases

  • Combining results from several requests: pages.flatMap(p => p.items).
  • Expanding nested data like categories and their products.
  • Turning a tree of menu items into a flat list (with recursion, or flat(Infinity) for plain nested arrays).

Interview angle

You may be asked to implement flattening without flat: recursion with reduce, or an iterative version using a stack (see "Flatten a nested array").

Code example

js
1const nested = [1, [2, [3, [4, [5]]]]];
2
3console.log(nested.flat()); // [1, 2, [3, [4, [5]]]]
4console.log(nested.flat(2)); // [1, 2, 3, [4, [5]]]
5console.log(nested.flat(Infinity)); // [1, 2, 3, 4, 5]
6
7console.log([1, , 3, [4, , 6]].flat()); // [1, 3, 4, 6] - holes removed
8
9// flatMap: map + flatten one level
10const orders = [
11 { id: 1, items: ["pen", "book"] },
12 { id: 2, items: [] },
13 { id: 3, items: ["lamp"] },
14];
15console.log(orders.flatMap((o) => o.items)); // ["pen", "book", "lamp"]
16
17// flatMap as filter + map in one pass
18const nums = [1, 2, 3, 4, 5, 6];
19console.log(nums.flatMap((n) => (n % 2 === 0 ? [n * 10] : []))); // [20, 40, 60]
20
21// Expand one item into several
22const sentences = ["hello world", "flat map"];
23console.log(sentences.flatMap((s) => s.split(" "))); // ["hello", "world", "flat", "map"]

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.

Open in study app