4

I have a similar issue as in Updating SVG Element Z-Index With D3

My preferred solution would be to have two groups within my svg as described in the answer by notan3xit.

But I have one data set, and a boolean flag on one of the data properties determines to which group the svg element belongs.

svg.selectAll("path")
   .data(d)
   .enter()
   .if(d.property).appendToGroup1() 
   .else.appendToGroup2()

This obviously doesn't work, but something like this.

I only want to iterate through the data once, and during runtime append the generated svg elements to the according groups.

Any ideas how to go about achieving that with d3.js?

Community
  • 1
  • 1
Rafael Emshoff
  • 2,541
  • 1
  • 35
  • 47
  • 3
    I would use the `.filter()` function to separate the groups, i.e. filter the data before you bind it to the elements. – Lars Kotthoff May 27 '15 at 16:18

2 Answers2

3

Try

.each(function(d){
  var toAppend = $(this);
  if (!!d.property){
    toAppend.appendtoGroup1();
  } else {
    toAppend.appendToGroup2();
  }
  })//...

The general idea would be to pass d into a callback, and apply the right append method inside that callback. It should be cleaner to first save reference to what you want to append to, in an enclosing scope so you can easily call .append() on it.

Sze-Hung Daniel Tsui
  • 2,282
  • 13
  • 20
2

Try this:

var selectedPath=svg.selectAll("path").data(d);
svg.selectAll("path").each(function(d,i){
      if(d3.select(this).attr("property's name"))
         selectedPath.append("some data to group 1")
      else
         selectedPath.append("some data to group 2") 
 });

If I had your code better able to help.

Gabriel
  • 1,413
  • 1
  • 18
  • 29