JSFiddle - React, Tailwind, and code Playground

by sg552sg552

HTML

<table>
  <thead>
    <tr>
      <th>string</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>C</td>
    </tr>
    <tr>
      <td>B</td>
    </tr>
    <tr>
      <td>A</td>
    </tr>

  </tbody>
</table>
<br/>

CSS

table,
td,
th {
  border: 1px solid black;
  border-collapse: collapse;
  padding: 2px 10px;
}

th {
  cursor: n-resize;
  background-color: lightgrey;
}

JavaScript

$('th').click(function() {  
  var table =  $(this).parents('table').eq(0);
  var rows = table.find('tr:gt(0)').toArray().sort(comparer($(this).index()));
  for (var i = 0; i < rows.length; i++) {
    table.append(rows[i]);    
  }
})

function comparer(index) {  
  return function(a, b) {      
    var valA = getCellValue(a, index),
      valB = getCellValue(b, index);
    return $.isNumeric(valA) && $.isNumeric(valB) ?  
      valA - valB  : 
      valA.localeCompare(valB)  ;
  }
}

function getCellValue(row, index) {
  return $(row).children('td').eq(index).html();
}