I'm working with D3.js and trying to sort my bars in ascending/descending order when a button is clicked. But I'm having issues having the sortBars function return the correct value from my object.
var sortOrder = false;
var sortBars = function() {
sortOrder = !sortOrder;
svg.selectAll("rect")
.sort(function(a, b) {
if (sortOrder) {
return d3.ascending(a, b);
} else {
return d3.descending(a, b);
}
})
.transition()
.delay(function(d, i) {
return i * 50;
})
.duration(1000)
.attr("x", function(d, i) {
return xScale(i);
});
};
When it returns xScale(i), I know it's not referencing my dataset appropriately. I've tried placing it as i.value (which is what I have it named as in my dataset). I know this isn't correct, but when I change it to that, I at least get the bars to move. How would I access the correct datum?
I've developed a JSFiddle for this. Feel free to play around with it. Currently, the Sort button won't have any effect (as the function is not correctly accessing the data yet).