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






