Autio
Autio

Reputation: 327

D3 Sorting Hierarchical Bars by Name instead of Value

I'm building a presentation tool based on the D3 hierarchical bar example: https://github.com/devsar/d3talk/blob/master/hierarchical-bar.html

What would be the best way to add an option to sort the hierarchy by name instead of value?

Upvotes: 2

Views: 1319

Answers (1)

jaime
jaime

Reputation: 42031

By default partion layouts are sorted by their associated numeric value, but you can set up your own comparator by calling sort which expect a function with two parameters to compare against each other.

To sort your bars by name, just change these lines

https://github.com/devsar/d3talk/blob/master/hierarchical-bar.html#L48-L49

to this

var hierarchy = d3.layout.partition()
  .value(function(d) { return d.size; })
  .sort(function(a, b){
      return a.name.toLowerCase() > b.name.toLowerCase();
  });

If you want to reverse the sort order, just return the opposite

  return a.name.toLowerCase() < b.name.toLowerCase();

Edit:

It seems when expanding the Query bar, some names weren't sorted correctly. Changing the return value of the comparator fixes it on my end (Chrome)

return a.name.toUpperCase().localeCompare(b.name.toUpperCase());

Upvotes: 1

Related Questions