How do I sort a bar chart?

Ok, this feels like a stupid question, but I have spent literally hours trying to figure this out and none of the answers I find seem to work.

I am trying to make a basic bar chart and can’t figure out how to sort the data in descending order.

You can see my progress and code here:

I just sent you a suggestion:

You just forgot to make websites use sortedData instead of data:slight_smile:

Thank you!

FYI in case anyone lands here from Google.

Part of what was driving me insane was that D3.js’s sort wasn’t sorting the data properly and left some items out of order.

For a better sort, import the “Zebra” library:

z = require('https://bundle.run/zebras@0.0.11')

And sort the data using this code structure:

sortedData = z.sortByCol('value', 'des', data).
// Explanation:
// z.sortByCol('Column to sort by', 'des (for descending) or asc (for ascending)', dataframe)

d3.sort doesn’t sort values that are not comparable (like null and undefined), but you can coerce null to the number 0:

sortedData = d3.sort(data, d => +d.LCP).reverse()

or

sortedData = d3.sort(data, d => -d.LCP ||0)

(Note: researching this I realize that there is a bug with d3.sort!)

Yes, my hunch is that the problem I was having was caused by null values.

The odd thing is that, instead of grouping the nulls together, d3.sort seems to have just gotten confused by them, with this result:

Thanks for all your help!

Exactly! The bug is filed as sort(A) and sort(A, d => d) are not equivalent · Issue #217 · d3/d3-array · GitHub