liveBook · Manning

Map

As explained in Secrets of the JavaScript Ninja, Second Edition

An Array method that creates a new array by applying a callback to each element.

Array.map calls a callback for each array item and returns a new array containing the callback’s return values. It avoids manually creating an output array and pushing transformed items into it. section 9.1.4

Extracting weapons

Transform ninja objects into an array of weapons: `const weapons = ninjas.map(ninja => ninja.weapon);` section 9.1.4

Listing 9.7. Mapping an array
const ninjas = [
  {name: "Yagyu", weapon: "shuriken"},
  {name: "Yoshi", weapon: "katana"},
  {name: "Kuma", weapon: "wakizashi"}
];

const weapons = ninjas.map(ninja => ninja.weapon);                    #A

assert(weapons[0] === "shuriken" 
    && weapons[1] === "katana"
    && weapons[2] === "wakizashi" 
    && weapons.length == 3, "The new array contains all weapons");

See the mapping example and its checks that the new array contains each weapon. section 9.1.4

How Secrets of the JavaScript Ninja, Second Edition covers it

How deep it goes
Defines callback-based transformation and demonstrates extracting object properties, without detailing further mechanics.
Examples
Extracts weapon names from an array of ninja objects and compares map with forEach and push.
What you can do after
Apply Array.map to transform an array of objects into an array of their weapon properties.
How it connects
Connects arrays, callbacks, and forEach as an alternative involving manual collection-building.

Also explained in

Compare how 8 books explain map →

Related concepts

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