d3: Performing .Sort by classes

匿名 (未验证) 提交于 2019-12-03 02:42:02

问题:

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.

回答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(); } 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!