liveBook · Manning

Map

As explained in Secrets of the JavaScript Ninja, Third Edition

A JavaScript method that creates a new array by applying a callback to each element of an array.

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

How Secrets of the JavaScript Ninja, Third Edition covers it

How deep it goes
Defines callback-to-result behavior and demonstrates it with a worked array example, without implementing the method itself.
Examples
Extracts weapon strings from an array of objects and compares the result with a for…of loop using push.
What it assumes
Assumes familiarity with arrays and callbacks; uses arrow functions and destructuring without teaching them from zero.
What you can do after
Apply it via JavaScript’s map method to create an array from callback return values.
How it connects
Contrasts map with forEach, flatMap, filter, and reduce as ways to process arrays.

Also explained in

Compare how 12 books explain map →

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.