Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 5.4 — Keys and Object Constancy
Data Visualization · Example 2 of 2

When keys go wrong, and sorting

Each report puts elements on the page, then joins new data with the same key function and counts the groups. No line throws: these are the silent failures.

Without a key, the join pairs by position, so when the data reorders or an item leaves, the wrong element gets the wrong item. A key function, such as (d) => d.id, pairs by identity, so each station keeps its own element.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 5 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

June's top stations are S01, S06, S04 and July's are S06, S01, S03. Write the keyed join code and say which elements are kept, entered and exited.

02

Write checkKeys(rows, key) that returns the keys that appear more than once. Test it with ids S01, S02, S01.

Explain it without notes

01

Why can a join without a key put the wrong value on a bar?

02

What makes a good key?

03

What does D3 do when two new items return the same key?

When keys go wrong, and sorting

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

A repeated among the elements: enter 0, update 2, exit 1
A repeated in the new data: enter 1, update 2, exit 0
numbers 1,2,3 <- strings '1','2','4': enter 1, update 2, exit 1
key returns the object itself: enter 2, update 1, exit 1
key reads a field the data lacks: enter 2, update 0, exit 2
order after join: cab
after sort: abc