score:2

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) {
  newData.push({
    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(a.id, b.id);
    });
  }
  //set the domain post sorting  
  x.domain(sorted.map(function(d) {
    return d.name;
  }))
  //sort the bars
  svg.selectAll("rect")
    .sort(function(a, b) {
      if (sortOrder) {
        return d3.descending(a.days, b.days);
      } else {
        return d3.ascending(a.id, b.id);
      }
    });
  //make transition
  var transition = svg.transition().duration(750),
    delay = function(d, i) {
      return i * 50;
    };

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

Working code here

Hope this helps!


Related Query

More Query from same tag