liveBook · Manning

Leaves()

As explained in D3.js in Action, Third Edition

leaves() is a hierarchy-node method that returns an array containing the hierarchy's leaf nodes.

leaves() is a hierarchy-node method that returns an array containing every node without children. Call it on the root returned by d3.stratify() or d3.hierarchy(). section 11.1.2 section 11.1.1

Collecting leaf nodes

After creating a hierarchy, store the terminal nodes alongside the root and all descendants: const root = hierarchy(data); const descendants = root.descendants(); const leaves = root.leaves(); With the language hierarchy, leaves include English, Mandarin Chinese, Hindi, Spanish, and French. section 11.1.2

{
  "name": "Languages",
  "children": [
    {
      "name": "Indo-European",
      "children": [
        {
          "name": "Germanic",
          "children": [
            {
              "name": "English"
            }
          ]
        },
        {
          "name": "Indo-Aryan",
          "children": [
            {
              "name": "Hindi"
            }
          ]
        },
        {
          "name": "Romance",
          "children": [
            {
               "name": "Spanish"
            },
            {
               "name": "French"
            }
          ]
        },
      ]
    },
    {
      "name": "Sino-Tibetan",
      "children": [
        {
          "name": "Sinitic",
          "children": [
            {
              "name": "Mandarin Chinese"
            }
          ]
        }
      ]
    }
  ]
}

Inspect the nested JSON structure whose objects without children become the hierarchy's leaves. section 11.1.2

How D3.js in Action, Third Edition covers it

How deep it goes
Defines the returned array and demonstrates its placement beside descendants(), but stops short of detailing node internals.
Examples
Uses language nodes such as English, Hindi, Spanish, French, and Mandarin Chinese as leaves.
What it assumes
Assumes basic JavaScript arrays and hierarchy nodes while teaching the terminal-node distinction from the hierarchy root.
What you can do after
Apply it via d3-hierarchy to collect terminal nodes from CSV- or JSON-derived hierarchies.
How it connects
Connects hierarchy, descendants(), d3.stratify(), d3.hierarchy(), and hierarchical visualizations.

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.