1

我正在尝试使用 sort 函数按升序对表中的行进行排序。

var forsort = d3.keys(csv[0]).filter(function(key) {
    return key != "name";
});

var tr = d3.selectAll("tbody tr");      
d3.selectAll("thead th").data(forsort).on("click", function(k) {
    tr.sort(d3.ascending);
});

由于某种原因,18 行中只有 3 行被交换(准确地说是第 2、3、11 行),第 2 行是第一个可排序的行。

有人可以告诉我可能是什么问题吗?

4

1 回答 1

2

From the d3 documentation, d3.ascending looks like this

function(a, b) {
  return a < b ? -1 : a > b ? 1 : 0;
}

What are a and b in your case? You can check by, instead, sorting like this:

tr.sort(function(a,b){ console.log('compare', a, b); });

I'm guessing that a and b are objects, in which case sorting them with greater/less -than would be meaningless.

Edit:

To sort by the key of the column that was clicked, you need to use the k attribute you're getting from the click handler (I have no way of verifying this, but I'm pretty sure that's what k is – a string corresponding to the column/attribute name).

So, ditch the use of d3.ascending and do the sorting like this:

tr.sort(function(a, b) {
  return a[k] < b[k] ? -1 : a[k] > b[k] ? 1 : 0;
})

Alternatively, you can still use d3.ascending like this:

tr.sort(function(a, b) {
  return d3.ascending(a[k], b[k]);
})

It's not much of a difference in principle. But, one benefit of the latter is that it makes it easier to implement something that'll give users control over sort direction (ascending vs descending). Something like this:

var sortFunction = d3.ascending;
// Instead of the line above, you could write some logic
// to decide whether sortFunction is d3.ascending or d3.descending

// Then you can write:
tr.sort(function(a, b) {
  return sortFunction(a[k], b[k]);
})
于 2012-10-23T05:30:00.830 回答