d3.table.Sort.onClick.201702211505

Sort by header item of clicked table.

by ytyaru

HTML

<script src="http://d3js.org/d3.v4.min.js"></script>
<p>Click any column in the table. Sort in ascending order by that column.</p>
<table id="License">
  <tr><th>Library</th><th>License</th><th>Copyright</th></tr>
  <tr><th><a href="https://d3js.org/">d3.js</a></th><th><a href="https://opensource.org/licenses/BSD-3-Clause">BSD-3-Clause</a></th><th><a href="https://github.com/d3/d3/blob/master/LICENSE">Copyright 2010-2016 Mike Bostock</a></th></tr>
</table>

CSS

#NameList { border-collapse: collapse; }
#NameList th { background-color: #CCC; }
#NameList td, 
#NameList th {
  border-collapse: collapse;
  border: 1px #CCC dotted;
  padding: 6px;
}
#License {
  margin-top: 30px;
}
#License td,
#License th {
  padding: 2px;
  font-size: 10px;
}

JavaScript

var objs = [
  {"id": 0, "name": "うえだ", "class": "B"},
  {"id": 1, "name": "あいだ", "class": "C"},
  {"id": 2, "name": "いいだ", "class": "A"}];
var sortInfo = { key: "id", order: d3.descending };

var table = d3.select("body").insert("table",":first-child").attr("id","NameList");
var thead = table.append("thead");
var tbody = table.append("tbody");

thead.append("tr")
  .selectAll("th")
    .data(d3.entries(objs[0]))
    .enter()
    .append("th")
    .on("click", function(d,i){createTableBody(d.key);})
    .text(function(d){return d.key;})
;
createTableBody("id");

function createTableBody(sortKey)
{
  if (sortInfo.order.toString() == d3.ascending.toString())
    { sortInfo.order = d3.descending; }
  else { sortInfo.order = d3.ascending; }
  objs.sort(function(x,y){return sortInfo.order(x[sortKey], y[sortKey])});
  // 新規作成する
  tbody
    .selectAll("tr")
      .data(objs)
      .enter()
      .append("tr")
    .selectAll("td")
      .data(function(d){return d3.entries(d)})
      .enter()
      .append("td")
      .text(function(d){return d.value;})
    ;
  // 更新する
  tbody
    .selectAll("tr")
      .data(objs)
    .selectAll("td")
      .data(function(d){return d3.entries(d)})
      .text(function(d){return d.value;})
    ;
}