Need one value from each item in an array? JavaScript’s map method calls a callback for each item and creates a new array from the callback’s return values. Use it to describe the result you want rather than building an output array with a loop and push. section 10.1.4
Listing 10.5 Deriving an array with map
const ninjas = [
{ name: "Yagyu", weapon: "shuriken" },
{ name: "Yoshi", weapon: "katana" },
{ name: "Kuma", weapon: "wakizashi" },
];
const weapons = ninjas.map(({ weapon }) => weapon); #A
console.assert(
weapons[0] === "shuriken" &&
weapons[1] === "katana" &&
weapons[2] === "wakizashi",
"Every ninja's weapon is included",
);
The callback extracts each object’s weapon. Its returned strings become the entries of the new weapons array. section 10.1.4
Choose the array operation by the result you need:
- Use map to produce a new array of callback results. Unlike forEach, the callback’s return value matters. section 10.1.4
- Use flatMap when each item can contribute an array of values that should be combined into one array. section 10.1.4
- Use filter to keep items meeting a condition, or reduce to combine items into a single value. section 10.1.4











