2

I have a table where my headers are in the first column. I search a method to sort my table by this column. I know datatable and tablesorter, but I don't find any solution with it to sort my table like this.

To be clear, here is an example of my table :

Name | John | Jane | Toto
Value| 1256 |  125 | 8563
Val2 |   12 |   45 |    3

(Here a beginning of code on JSFiddle : https://jsfiddle.net/nLwo8bya/1/)

And I want to click on a cell in the first column to sort other column by this row.

If I click on the name, the previous table will be :

Name | Jane | John | Toto
Value|  125 | 1256 | 8563
Val2 |   45 |   12 |    3

The column of table are now sort by name (the first row in this case).

Thanks in advance for your help

Edit : Like nnnnnn says, I want to sort columns, by the first one

DSX
  • 139
  • 4
  • 1
    Possible duplicate of [Sorting table rows according to table header column using javascript or jquery](http://stackoverflow.com/questions/24033294/sorting-table-rows-according-to-table-header-column-using-javascript-or-jquery) – dlsso Jul 22 '16 at 23:20
  • @disso - That other question is not a duplicate: that one sorts rows with the top row as column headings, but OP here wants to sort columns, with first column as row headings. – nnnnnn Jul 22 '16 at 23:22
  • Yes, I flagged on accident and there is no 'un-flag' option. However, it would still be a good starting point for DSX to work from. DSX, my personal suggestion would be to change the format of the table and use a plugin that does column sorting. – dlsso Jul 22 '16 at 23:26
  • @dlsso : I know how to sort my table "normally", but I don't know how to sort with a click on the first column to change the order of the others. I hope I'm clear because of my bad english... – DSX Jul 22 '16 at 23:30
  • Your question is clear, don't worry. The answer is that you would do something like the answers I linked, but use row instead of column. The easier solution is to change the layout of your table and just sort by column. – dlsso Jul 22 '16 at 23:33
  • Yes I think about this solution, but in my case, I really want to save this layout. But if there are no solution, I will have to change my layout :-( – DSX Jul 22 '16 at 23:43
  • Not an optimal solution, but you may think on transposing the table, sorting it by rows and then transposing it again. You may find how to transpose it [here](http://stackoverflow.com/a/17428705/6481438). – GCSDC Jul 23 '16 at 00:24
  • @GCSDC : Thank you for this proposition, I keep it if my first wish is not possible – DSX Jul 23 '16 at 00:35

2 Answers2

0

The first way that came to mind was to restructure the table such that you end up with one row with one td per column; each of these column tds would contain a nested table with the data for that column. That way the actual sort process is very simple because you just have to sort the top-level tds.

The complicated part is the restructure. Following is just the first ugly bunch of code that I wrote to make that happen. This can probably be tidied up and optimised quite a lot, or completely rewritten in a smarter way, but I leave that as an exercise for the reader...

$(document).ready(function(){
  var trs = $("table tr");
  var tds = trs.find("td");
  var columnCount = trs.first().children().length;
  var columns = [];
  var sortableTR = $("<tr></tr>");
  for (var i = 0; i < columnCount; i++)
    columns.push([]);

  tds.each(function(i,td) {
    columns[i%columnCount].push($("<tr></tr>").append(td));
  });  
  columns.forEach(function(v) {
    sortableTR.append($("<td></td>").append($("<table></table>").append(v)));
  });
  trs.remove("tr");
  $("table").append(sortableTR);
  sortableTR.children().first().on("click", "tr", function(e) {
    var row = $(this);
    var rowIndex = row.index();
    var dataType = row.find("td").attr("data-type");
    var cols = sortableTR.children().slice(1);
    cols.sort(function(a, b) {
      a = $(a).find("td").eq(rowIndex).text();
      b = $(b).find("td").eq(rowIndex).text();
      if (dataType==="number") {
        a = +a;
        b = +b;
      }
      return a > b ? 1 : a < b ? -1 : 0;
    });
    cols.each(function() { sortableTR.append(this); });
  });
});
table, tr, td { border: none; border-collapse: collapse; }
td { width: 100px; padding: 0px; margin: 0px; }
td td { border: thin grey solid; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<table border="1">
<tr><td data-type="string"><b>Name</b></td><td>John</td><td>Jane</td><td>Jack</td></tr>
<tr><td data-type="number"><b>Age</b></td><td>36</td><td>34</td><td>42</td></tr>
<tr><td data-type="number"><b>Weight</b></td><td>111</td><td>56</td><td>82</td></tr>
<tr><td data-type="number"><b>Score</b></td><td>25</td><td>42</td><td>18</td></tr>
</table>

Note that I added a data-type attribute to the heading cells so that the sort knows whether to treat the data as numeric or not.

Fixing the styles on the resulting table is another thing I leave as an exercise for the reader...

nnnnnn
  • 147,572
  • 30
  • 200
  • 241
  • Thank you so much for your code. I will adapt to my table and probably add data-* to sort correctly. And with this beginning of code, I will add the possibility to sort in the both way (ascending and descending). – DSX Jul 23 '16 at 08:32
0

Sort columns

 // create headings array to sort
 var headings = $('#sortedTable tr:first td:gt(0)').map(function(item){       
       return $(this).text()
  }).get();
  // copy  and sort new array
  var sortedHeadings = headings.slice().sort();
  // create object where old index is key, value is new index
  var indices =  headings.reduce(function(a,c,i){
     a[i]= sortedHeadings.indexOf(c);
     return a;
  },{});
  // iterate rows and sort cells
  $('#sortedTable tr') .each(function(i){
     // sort using index hash object above
     var $cells = $(this).children(':gt(0)').sort(function(a,b){
         return indices[$(a).index()]-indices[$(b).index()]
     });
     // append sorted cells
     $(this).append($cells)
  });

DEMO

charlietfl
  • 170,828
  • 13
  • 121
  • 150
  • Thank you for your code. I will try to test this with my table and add the listener to the headers to sort the table when I click on the cell like the proposition of nnnnnn. – DSX Jul 23 '16 at 08:36
  • Can you explain me why you use the slice() function at this line : `code`var sortedHeadings = headings.slice().sort();`code` – DSX Jul 23 '16 at 09:05
  • To make array copy – charlietfl Jul 23 '16 at 09:06
  • Oh ok, obvious. I'm reading your code and documentation about reduce function but I don't understand it. Cans you explain me briefly please ? – DSX Jul 23 '16 at 09:21
  • The comments explain what it is doing. See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce – charlietfl Jul 23 '16 at 12:25
  • Ok thank you for this documentation and your explanations – DSX Jul 23 '16 at 12:37