neubert
neubert

Reputation: 16802

Trying to understand D3's selection.data() works

I have as my HTML this:

<div>1</div>
<div>10</div>

My JS:

divs = d3.select("body").selectAll("div");
alert(divs[0].length);

divs = divs.data([2]);
alert(divs[0].length);

My js fiddle:

http://jsfiddle.net/p2v3B/

D3's documentation - https://github.com/mbostock/d3/wiki/Selections#wiki-data - suggests that selection.data() "joins the specified array of data with the current selection" however this test would seem to suggest it's not joining anything but rather flat out replacing it.

ie. there's two divs and then after doing data() there's just one?

Upvotes: 0

Views: 61

Answers (1)

Lars Kotthoff
Lars Kotthoff

Reputation: 109252

The way the join works is that it tries to match the given data to existing elements. If you give only one data item, it can match at most one. In your case, the 2 is matched by the first existing element (because by default d3 matches based on index within the array) and the other div is part of the .exit() selection.

The intention is that you use this when updating the displayed data. Previously, there were two data items, now there's only one. The one that would be updated in some way whereas the other one would be deleted.

If you haven't done so already, I recommend having a look at the three little circles tutorial which explains and illustrates these concepts in more detail.

Upvotes: 2

Related Questions