liveBook · Manning

Key function

As explained in D3.js in Action, Third Edition

A key function computes stable identity keys that allow data-bound elements to be matched with corresponding data items across updates.

A key function computes a stable identity for each datum so D3 can keep data-bound elements matched with the same data across updates. Without one, D3 matches elements and data by position: the first circle receives the first updated datum, the second receives the second, and so on. With a key such as each cetacean’s uid, circles that remain visible continue representing the same cetacean. section 7.4.2

Keep filtered scatterplot points attached to their data

Pass the key function as the second argument to data(): innerChart .selectAll("circle") .data(updatedData, d => d.uid) .join("circle"); When filters change the cetacean dataset, circles that remain on the scatterplot keep their associated data instead of changing identity. New points enter, existing points update, and removed points exit.

How D3.js in Action, Third Edition covers it

How deep it goes
Explains positional matching, uid-based matching, and integration with D3 data() and join(), without descending into API internals.
Examples
Uses filtered cetacean circles keyed by uid and compares D3 matching with React list keys.
What you can do after
Apply it via D3's data() method to preserve element identity during dataset updates and control resulting selections.
How it connects
Connects data binding with the DOM, scatterplot filtering, and enter, update, and exit selections.

Also explained in

Compare how 2 books explain key function →

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.