drew moore
drew moore

Reputation: 32670

D3 leaves wrong elements on screen

My d3 selection starts with a large dataset, appending a circle to my SVG for each element in it and setting the ID of the circle element to match the ID of the data item it represents.

Then, I call .data() on that same selection, passing in a smaller subset of the original. As expected, the number of circles on the screen after I do so matches the number of items in the smaller dataset. However, when I inspect the elements on the screen, their IDs do not match the IDs of the items in the new dataset.

Why might this be?

Upvotes: 0

Views: 35

Answers (1)

Felix Kling
Felix Kling

Reputation: 816344

If you don't pass a key function to data, the data is associated to existing elements via their position.

You probably want something like

.data(data, function(d) { return d.id; });

From the documentation:

To control how data is joined to elements, a key function may be specified. This replaces the default by-index behavior; the key function is invoked once for each element in the new data array, and once again for each existing element in the selection.

Upvotes: 1

Related Questions