d3.js

d3 selectAll().data() just returns data in first element. why


I am trying to get the data for all of the matching elements using d3. I have the following code:

d3.selectAll('svg').selectAll('.line').data()

What I expect is that it should return data for all of the matching elements. But it just returns data for the first matching element.

If I just do:

d3.selectAll('svg').selectAll('.line')

this shows that it has 2 group elements and their data property contains the data.

If I just do var line = d3.selectAll('svg').selectAll('.line'); line[0].data(), it throws an error. This is because line[0] becomes a DOM element without any property.

How do I get data for all matching selections, or am I just not clear on how to use this selector?


Solution

  • This is the expected behaviour as the spec on selection.data(values) reads:

    If values is not specified, then this method returns the array of data for the first group in the selection.

    That explains why you only get the data bound to the first group.

    To access data bound to all groups returned by your selection you could use:

    d3.selectAll('svg').selectAll('.line').each(function(d) {
        // Within this function d is this group's data.
        // Iterate, accumulate, do whatever you like at this point.
    });