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]);
})