Sergei Basharov
Sergei Basharov

Reputation: 53850

Pass current element index to a function in D3

I use code from this example to create a set of independent lines as path elements:

svgContainer.append("path")
            .attr("d", lineFunction(lineData))
            .attr("stroke", "blue")
            .attr("stroke-width", 2)
            .attr("fill", "none");

As I have all lines data in lineData array, in each iteration I want to pass only a single item from it, like lineFunction(lineData[i]). My question is how can I get this current index as I can usually do with someFunction(d, i){} in D3?

Upvotes: 2

Views: 1491

Answers (1)

meetamit
meetamit

Reputation: 25157

You need to first bind to lineData in the typical d3 way. So:

svgContainer.selectAll('path').data(lineData).enter()
  .append("path")
    .attr("d", lineFunction)
    .attr("stroke", "blue")
    .attr("stroke-width", 2)
    .attr("fill", "none");

On the line

    .attr("d", lineFunction)

lineFunction the gets called with d and i as params, where d is the element in the array (which, if I understood, is an array of points). It's the same as doing

    .attr("d", function(d,i) { return lineFunction(d); }

which is the same as

    .attr("d", function(d,i) { return lineFunction( lineData[i]); }

Upvotes: 2

Related Questions