I am trying to use the sort function to sort rows in a table in ascending order.
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);
});
For some reason only 3 rows out of 18 are being swapped (rows 2,3,11 to be precise) with row 2 being the first sortable row.
Can someone tell me what the problem can be?
From the d3 documentation,
d3.ascendinglooks like thisWhat are
aandbin your case? You can check by, instead, sorting like this:tr.sort(function(a,b){ console.log('compare', a, b); });I’m guessing that
aandbare 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
kattribute you’re getting from the click handler (I have no way of verifying this, but I’m pretty sure that’s whatkis – a string corresponding to the column/attribute name).So, ditch the use of d3.ascending and do the sorting like this:
Alternatively, you can still use d3.ascending like this:
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: