0

I am trying to understand how the .sort() method works.

My implementation should be very simple, using the method:

.sort(function (a, b) { 

  });

I want to check whether the element is a member of a certain class. If it is, I want it to be put towards the top. Otherwise, it should go to the bottom. What's the pattern?

The sort is on a path group of states from a geojson projection:

d3.json("./data/states.json", function(us) {

        mapSvg.selectAll("path")
                       .data(us.features)
                       .enter()
                       .append("path")
                       .attr("d", path).attr("class",function(d){return "border2 thestates"})

        });
   }

I want to bring some of the states to the front if they have a class.

Union find
  • 7,759
  • 13
  • 60
  • 111

1 Answers1

1

The return value of the .sort() function should be as follows (from the documentation):

It should return either a negative, positive, or zero value. If negative, then a should be before b; if positive, then a should be after b; otherwise, a and b are considered equal and the order is arbitrary.

So in your case, it should be something like this:

function(a, b) {
  if(a.memberOfClass() && !b.memberOfClass()) {
    return -1;
  } else if(b.memberOfClass()) {
    return 1;
  } else {
    return 0;
  }
}

You can simplify this because true also evaluates to 1:

function(a, b) {
  return -a.memberOfClass() + b.memberOfClass();
}
Lars Kotthoff
  • 107,425
  • 16
  • 204
  • 204
  • Thanks. I don't know why I was making this so complicated. I went with a variant on the simplified code. You could also use a ternary operator in the first option. – Union find Nov 13 '14 at 18:17