guyforlowbro
guyforlowbro

Reputation: 361

Best way to prevent looping using D3

I'm relatively new to D3, and I'm wondering about the best way to prevent code like this. Often I rarely see people loop in D3.js. However I haven't quite yet understood why they don't have to. Given this code I have is it necessary to loop? or is there a way to prevent looping like so? have the following code snippet:

var tickPath = svg.selectAll('.tickPath')
    .data(tickValues)
    .enter().append('path')
    .attr('class', 'tickPath')
    .attr('d', function(d) {
      var tickArray = [];
      for (var i = 0; i < numBars; i++) tickArray.push({c : d});
      return area(tickArray);
    })
    .style('fill', (d) => color(d))
    .style('stroke', (d, i) => (i === 0) ? 'black' : '#5e5e5e')
    .style('stroke-width', (d, i) => (i === 0) ? '1px' : '.5px');

Upvotes: 0

Views: 145

Answers (1)

Lukasz Wiktor
Lukasz Wiktor

Reputation: 20422

You don't see code like yours because people usually use the axis component instead of building one from scratch.

Another thing is that selections encapsulate looping. From d3's docs:

You won't generally need to use for loops or recursive functions to modify the document with D3. That's because you operate on entire selections at once, rather than looping over individual elements. However, you can still loop over elements manually if you wish.

However, a SVG path is a single element so a d3 selection won't help to avoid/hide looping in your case.

Upvotes: 2

Related Questions