liveBook · Manning

Flatmap

As explained in Secrets of the JavaScript Ninja, Third Edition

flatMap is an array method that maps each element to a value and flattens the resulting arrays by one level.

Need one output array from inputs that each contribute several values—or none? JavaScript’s `flatMap` calls a callback for each array item and flattens the resulting arrays by one level. A callback that returns `[]` contributes nothing; one that returns multiple items contributes them all. section 10.1.4

Think of it as `map` followed by `flat()`. Unlike `map`, which produces one result per input, `flatMap` supports zero-to-many results in a single operation. Flattening is only one level deep; deeper nested arrays remain nested. section 10.1.4

Listing 10.6 Deriving an array with flatMap
const ninjas = [
  { name: "Yagyu", weapons: ["shuriken", "kunai"] },
  { name: "Yoshi", weapons: [] },
  { name: "Kuma", weapons: ["katana", "tanto"] },
];
 
const weapons = ninjas.flatMap(({ weapons }) => weapons);  #A
console.assert(
  weapons[0] === "shuriken" &&
    weapons[1] === "kunai" &&
    weapons[2] === "katana" &&
    weapons[3] === "tanto",
  "All ninja weapons are included",
);

The weapons example collects each person’s array into one result. The empty array contributes no weapons, while the other arrays contribute two each. section 10.1.4

How Secrets of the JavaScript Ninja, Third Edition covers it

How deep it goes
Explains callback results and one-level flattening, but does not detail the optimized operation’s internals.
Examples
Demonstrates collecting weapons from objects that hold two weapons or none.
What it assumes
Builds on map callbacks and uses arrow-function destructuring, with a destructuring refresher deferred to MDN.
What you can do after
Apply it via JavaScript Array.flatMap to collect zero or more values per input into one array.
How it connects
Connects flatMap to map, flat, reduce, loops, and chained array methods.

Also explained in

Compare how 7 books explain flatmap →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Secrets of the JavaScript Ninja, Third Edition. The section links point to the parts of the book it draws on.