Accepted answer

First of all rather than having 2 different arrays of presidents and its data. Lets make it into single object so tat sorting is easy.

var newData = [];
data.names.forEach(function(d, i) {
    name: d,//now object will have a name
    days: data.days[i],//days will hold the president data
    id: i //id of the record for chronology sorting

Now for sorting do this:

var sortBars = function() {

    if (sortOrder){
    //sort on basis of date
    var sorted = newData.sort(function(a, b) {
            return d3.descending(a.days, b.days);
  } else {
    //sort on basis of id
    var sorted = newData.sort(function(a, b) {
            return d3.ascending(,;
  //set the domain post sorting  
  x.domain( {
  //sort the bars
    .sort(function(a, b) {
      if (sortOrder) {
        return d3.descending(a.days, b.days);
      } else {
        return d3.ascending(,;
  //make transition
  var transition = svg.transition().duration(750),
    delay = function(d, i) {
      return i * 50;

  //transition dor xa axis labels".x.axis")
    .style("text-anchor", "end")
    .attr("dx", "-.9em")
    .attr("dy", ".25em")
    .attr("transform", "rotate(-50)")
  //transition for bars.
    .attr("transform", function(d, i) {
      return "translate(" + i * barWidth + ",0)";

Working code here

Hope this helps!

Related Query

More Query from same tag