d3 selectAll: count results

One way I have done this previously is to pass that information into the data function by making a new object.

 .data(function(d) {         
     return d.Objects.map(function(obj) {
         return {
             Object: obj,
             TotalObjects: d.Objects.length
         }
   });

Then in your update portions you use Object and still have the count available.

.attr("x", function(d) {

    return d.Object.X;
 })
 .attr("y", function(d) {

    return d.TotalObjects;
 })

To get the data count, then after .selectAll() and .data(), it appears that .enter() is needed before .size():

legend_count = legendBoxG.selectAll("legend.box")
                         .data(curNodesData, (d) -> d.id)
                         .enter()
                         .size()

Without the .enter(), the result is 0. The .enter() makes it return the data count. (Code above is shown in Coffee dialect.)

I need to get the count before adding attributes to my svg objects (in order to scale them properly), and none of the preceding examples did that. However I can't seem to add more attributes after stripping out the count into a variable as above. So while the above approach demonstrates the operation of data() and enter() it isn't really a practical solution. What I do instead is to get the length of the data array itself before doing the selectAll(). I can do that most simply with the length property (not a function) on the data array itself:

 legend_count = curNodesData.length

Just use d3.selectAll(data).size().Hope this example help you:

 var matrix = [
   [11975,  5871, 8916, 2868],
   [ 1951, 10048, 2060, 6171],
   [ 8010, 16145, 8090, 8045],
   [ 1013,   990,  940, 6907]
 ];

 var tr = d3.select("body").append("table").selectAll("tr")
            .data(matrix)
            .enter().append("tr");

 var td = tr.selectAll("td")
          .data(function(d) { return d; })
          .enter().append("td")
          .text(function(d) { return d; });
 var tdSize=tr.selectAll("td").size();

Complete jsfiddle here.