I need the index of the current selection's parent. I have read that I can use the third parameter of the .attr()
function but I get an array of objects instead of an integer index.
I use D3 version 3.
At the moment the code is:
function positiveBars(x, y, n, svgElement, colors) {
IndexA = -1; //<--
IndexB = -1; //<--
svgElement.selectAll(".positiveBar")
.data(function(d){ return d; })
.enter()
.append("rect")
.attr("x", function(d, i, j){
if(i == 0) {IndexA++;} //<--
console.log(j); //<--
return x(d.time) + x.bandwidth() / n *IndexA;
})
.attr("width", x.bandwidth() / n)
.attr("y", function(d) { return y(d.y); })
.attr("height", function(d){ return y(0)- y(d.y); })
.attr("class","positiveBar")
.attr("fill",function(d, i, j) {
if(i == 0) {IndexB++;} //<--
return colors ? colors[IndexB] : '#111';
})
}
The log gives me:
Using IndexA
and IndexB
it works but not like I want it. How can I get the right value of the j
variable?