26

The description of the selection.data function includes an example with multiple groups (link) where a two-dimensional array is turned into an HTML table.

In d3.js v3, for lower dimensions, the accessor functions included a third argument which was the index of the parent group's datum:

td.text(function(d,i,j) {
  return "Row: " + j;
});

In v4, this j argument has been replaced by the selection's NodeList. How do I access the parent group's datum index now?

8 Answers 8

19

Well, sometimes an answer doesn't provide a solution, because the solution may not exist. This seems to be the case.

According to Bostock:

I’ve merged the new bilevel selection implementation into master and also simplified how parents are tracked by using a parallel parents array.

A nice property of this new approach is that selection.data can evaluate the values function in exactly the same manner as other selection functions: the values function gets passed {d, i, nodes} where this is the parent node, d is the parent datum, i is the parent (group) index, and nodes is the array of parent nodes (one per group). Also, the parents array can be reused by subselections that do not regroup the selection, such as selection.select, since the parents array is immutable.

This change restricts functionality—in the sense that you cannot access the parent node from within a selection function, nor the parent data, nor the group index — but I believe this is ultimately A Good Thing because it encourages simpler code.

(emphasis mine)

Here's the link: https://github.com/d3/d3-selection/issues/47

So, it's not possible to get the index of the parent's group using selection (the parent's group index can be retrieved using selection.data, as this snippet bellow shows).

var testData = [
[
  {x: 1, y: 40},
  {x: 2, y: 43},
  {x: 3, y: 12},
  {x: 6, y: 23}
], [
  {x: 1, y: 12},
  {x: 4, y: 18},
  {x: 5, y: 73},
  {x: 6, y: 27}
], [
  {x: 1, y: 60},
  {x: 2, y: 49},
  {x: 3, y: 16},
  {x: 6, y: 20}
 ] 
];

var svg = d3.select("body")
	.append("svg")
  .attr("width", 300)
  .attr("height", 300);
  
var g = svg.selectAll(".groups")
    .data(testData)
    .enter()
    .append("g");
    
var rects = g.selectAll("rect")
    .data(function(d, i , j) { console.log("Data: " + JSON.stringify(d), "\nIndex: " + JSON.stringify(i), "\nNode: " + JSON.stringify(j)); return d})
    .enter()
    .append("rect");
<script src="https://d3js.org/d3.v4.min.js"></script>

2
  • 1
    I hadn't seen that issue so thanks for pointing it out. Using .each() to circumvent this restriction would make my code quite ugly but I guess at this point, there's no other way.
    – Oliver
    Jul 7, 2016 at 7:32
  • 2
    But how do you the index into 'someFunc' in .append("rect").on("click", someFunc) Oct 18, 2016 at 2:55
12

My workaround is somewhat similar to Dinesh Rajan's, assuming the parent index is needed for attribute someAttr of g.nestedElt:

v3:

svg.selectAll(".someClass")
    .data(nestedData)
  .enter()
  .append("g")
    .attr("class", "someClass")
  .selectAll(".nestedElt")
    .data(Object)
  .enter()
  .append("g")
    .attr("class", "nestedElt")
    .attr("someAttr", function(d, i, j) {

    });

v4:

svg.selectAll(".someClass")
    .data(nestedData)
  .enter()
  .append("g")
    .attr("class", "someClass")
    .attr("data-index", function(d, i) { return i; }) // make parent index available from DOM
  .selectAll(".nestedElt")
    .data(Object)
  .enter()
  .append("g")
    .attr("class", "nestedElt")
    .attr("someAttr", function(d, i) {
      var j = +this.parentNode.getAttribute("data-index");
    });
1
  • Are there any form to access parent when using arrow operators? I.e.,.attr("someAttr", (d, i) => ???)
    – felipecrp
    May 19, 2019 at 16:33
4

I ended up defining an external variable "j" and then increment it whenever "i" is 0

example V3 snippet below.

rowcols.enter().append("rect")
 .attr("x", function (d, i, j) { return CalcXPos(d, j); })
 .attr("fill", function (d, i, j) { return GetColor(d, j); })

and in V4, code converted as below.

var j = -1;
rowcols.enter().append("rect") 
 .attr("x", function (d, i) { if (i == 0) { j++ }; return CalcXPos(d, j); })
 .attr("fill", function (d, i) { return GetColor(d, j); })
2
  • I think this only works if new rows are appended to the end of the table. If a row is inserted in the middle, it will receive the wrong "j" index. (This code also assumes a specific order in which d3.js processes the nodes. Since this is order is not documented anywhere, I'd be hesitant to use it.)
    – Oliver
    Feb 19, 2017 at 10:45
  • agree.. this is more or less a "hacky" way... guess will do if needing a quick and dirty conversion Feb 22, 2017 at 17:14
2

If j is the nodeList...

  • j[i] is the current node (eg. the td element),
  • j[i].parentNode is the level-1 parent (eg. the row element),
  • j[i].parentNode.parentNode is the level-2 parent (eg. the table element),

  • j[i].parentNode.parentNode.childNodes is the array of level-1 parents (eg. array of row elements) including the original parent.

So the question is, what is the index of the parent (the row) with respect to it's parent (the table)?

We can find this using Array.prototype.indexOf like so...

k = Array.prototype.indexOf.call(j[i].parentNode.parentNode.childNodes,j[i].parentNode);

You can see in the snippet below that the row is printed in each td cell when k is returned.

var testData = [
[
  {x: 1, y: 1},
  {x: 1, y: 2},
  {x: 1, y: 3},
  {x: 1, y: 4}
], [
  {x: 2, y: 1},
  {x: 2, y: 2},
  {x: 2, y: 3},
  {x: 2, y: 4}
], [
  {x: 3, y: 4},
  {x: 3, y: 4},
  {x: 3, y: 4},
  {x: 3, y: 4}
 ]
];

var tableData =
  d3.select('body').selectAll('table')
    .data([testData]);

var tables =
  tableData.enter()
  .append('table');

var rowData =
  tables.selectAll('table')
    .data(function(d,i,j){
      return d;
    });

var rows =
  rowData.enter()
  .append('tr');

var eleData =
  rows.selectAll('tr')
    .data(function(d,i,j){
      return d;
    });

var ele =
  eleData.enter()
  .append('td')
    .text(function(d,i,j){
      var k = Array.prototype.indexOf.call(j[i].parentNode.parentNode.childNodes,j[i].parentNode);
      return k;
    });
<script src="https://d3js.org/d3.v4.min.js"></script>

Reservations

This approach is using DOM order as a proxy for data index. In many cases, I think this is a viable band-aid solution if this is no longer possible in D3 (as reported in this answer).

Some extra effort in manipulating the DOM selection to match data might be needed. As an example, filtering j[i].parentNode.parentNode.childNodes for <tr> elements only in order to determine the row -- generally speaking the childNodes array may not match the selection and could contain extra elements/junk.

While this is not a cure-all, I think it should work or could be made to work in most cases, presuming there is some logical connection between DOM and data that can be leveraged which allows you to use DOM child index as a proxy for data index.

2
  • This is only giving me the position of the DOM node with respect to its parent DOM node. In some cases (like your example), it may be the right value but often enough, this will be wrong. What I need is the index into the data array that's bound to the DOM - in fact, that's why I'm using d3.js in the first place. As soon as my data array changes or when the parent node contains other child nodes, your method will fail.
    – Oliver
    Jul 8, 2016 at 6:06
  • Excellent points. I think in many cases this CAN work as a solution, but I agree with you that it is not an inherent solution as it's relying on using DOM index/order as a proxy for the data index. I wrote this answer as a possible work-around after reading @gerardo 's answer that the previous functionality may just not be there anymore. Jul 8, 2016 at 16:20
2

Here's an example of how to use the selection.each() method. I don't think it's messy, but it did slow down the render on a large matrix. Note the following code assumes an existing table selection and a call to update().

update(matrix) {
        var self = this;
        var tr = table.selectAll("tr").data(matrix);

        tr.exit().remove();

        tr.enter().append("tr");

        tr.each(addCells);

        function addCells(data, rowIndex) {
            var td = d3.select(this).selectAll("td")
                .data(function (d) {
                    return d;
                });
            td.exit().remove();

            td.enter().append("td");

            td.attr("class", function (d) {
                return d === 0 ? "dead" : "alive";
            });

            td.on("click", function(d,i){
                matrix[rowIndex][i] = d === 1 ? 0 : 1; // rowIndex now available for use in callback.                   
            });
        }

        setTimeout(function() {
            update(getNewMatrix(matrix))
        }, 1000);
    },
1
  • I like this as it doesn't require you to wrap your data elements into objects to hold references to their parent, but instead uses closures to access the index. The speed penalty could be due to issuing a lot of selectAll/exit/enter commands on tables with many rows but that's just a guess.
    – Oliver
    Feb 19, 2017 at 10:57
2

Assume you want to do a nested selectiom, and your data is some array where each element in turn contains an array, let's say "values". Then you have probably some code like this:

var aInnerSelection = oSelection.selectAll(".someClass") //
    .data(d.values) //
    ...

You can replace the array with the values by a new array, where you cache the indices within the group.

var aInnerSelection = oSelection.selectAll(".someClass") //
    .data(function (d, i) {
        var aData = d.values.map(function mapValuesToIndexedValues(elem, index) {
                return {
                    outerIndex: i,
                    innerIndex: index,
                    datum: elem
                };
            })
            return aData;
    }, function (d, i) {
        return d.innerIndex;
    }) //
    ...

Assume your outer array looks like this: [{name "X", values: ["A", "B"]}, {name "y", values: ["C", "D"]}
With the first approach, the nested selection brings you from here

                  d                                i
------------------------------------------------------------------
root dummy X      {name "X", values: ["A", "B"]}    0
     dummy Y      {name "Y", values: ["C", "D"]}    1

to here.

             d       i
------------------------------------------------------------------
root X  A    "A"     0
        B    "B"     1
     Y  C    "C"     2
        D    "D"     3

With the augmented array, you end up here instead:

             d                                              i
------------------------------------------------------------------
root X  A    {datum: "A", outerIndex: 0, innerIndex: 0}     0
        B    {datum: "B", outerIndex: 0, innerIndex: 1}     1
     Y  C    {datum: "C", outerIndex: 1, innerIndex: 0}     2
        D    {datum: "D", outerIndex: 1, innerIndex: 1}     3

So you have within the nested selections, in any function(d,i), all information you need.

1
  • This is actually what I end up doing in most of my code now. I would have liked for d3.js to provide a way to access the index (as it used to) instead of having to wrap every value into an extra object. But since that is gone now, I guess we'll have to go with this solution (@david004's answer may be a good alternative).
    – Oliver
    Feb 19, 2017 at 10:59
0

Here's a snippet I crafter after re-remembering this usage of .each for nesting, I thought it may be useful to others who end up here. This examples creates two layers of circles, and the parent group index is used to determine the color of the circles - white for the circles in the first layer, and black for the circles in the top layer (only two layers in this case).

const nested = nest().key(layerValue).entries(data);

let layerGroups = g.selectAll('g.layer').data(nested);
layerGroups = layerGroups.enter().append('g').attr('class', 'layer')
  .merge(layerGroups);

layerGroups.each(function(layerEntry, j) {   
  const circles = select(this)
    .selectAll('circle').data(layerEntry.values);
  circles.enter().append('circle')
    .merge(circles)
      .attr('cx', d => xScale(xValue(d)))
      .attr('cy', d => yScale(yValue(d)))
      .attr('r', d => radiusScale(radiusValue(d)))
      .attr('fill', j === 0 ? 'white' : 'black'); // <---- Access parent index.
});
0

My solution was to embed this information in the data provided to d3js

data = [[1,2,3],[4,5,6],[7,8,9]]
flattened_data = data.reduce((acc, v, i) => {
    v.forEach((d, j) => {
      data_item = { i, j, d };
      acc.push(data_item);
    });
    return acc;
  }, []);

Then you can access i, j and d from the data arg of the function

td.text(function(d) {
  // Can access i, j and original data here
  return "Row: " + d.j;
});

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.