liveBook · Manning

Map

As explained in D3.js in Action, Third Edition

The JavaScript map() method creates a new array by applying a callback to every element of an input array.

The JavaScript map() method creates a new array by applying a callback to every element of an input array. It is useful for reshaping loaded data into the values a visualization needs. section 1.2.5

Extracting names for a visualization

Given employee records in data, use data.map(d => d.name) to produce ["Zoe", "James", "Alice", "Hubert"]. The original records remain available while the new array supplies a simple list for positioning, labeling, or other chart tasks. section 1.2.5

Use map() when you need to:

  • Convert each datum into one selected property, such as an employee name. section 1.2.5
  • Create a scale domain from dataset values, such as each year in a chart. section 5.1.1
  • Keep every input element while changing the shape or value returned for each element; use filter() or find() for selection instead. section 1.2.5
data.map(d => d.name);   // => ["Zoe", "James", "Alice", "Hubert"]

Inspect the complete employee-name mapping and its resulting array. section 1.2.5

Listing 5.1 Declaring the band scale (scales.js)
const xScale = d3.scaleBand();  #1

const defineScales = (data) => {
  xScale
    .domain(data.map(d => d.year))  #2
    .range([0, innerWidth]);       
};

See map() connect loaded years to a D3 band scale domain, making the extracted values drive chart positioning. section 5.1.1

How D3.js in Action, Third Edition covers it

How deep it goes
Defines callback-based array transformation with working results, but stops short of broader array and object manipulation techniques.
Examples
Uses employee names and dataset years as mapped arrays for labels, scale domains, and chart positioning.
What it assumes
Assumes basic JavaScript arrays, objects, properties, and callbacks while grounding the technique in loaded datasets.
What you can do after
Apply it via JavaScript to reshape array data for D3 scales and other visualization operations.
How it connects
Connects arrays and data wrangling with filter(), find(), D3 scales, and visualization positioning.

Also explained in

Compare how 8 books explain map →

Related concepts

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