I'm after a table sorting solution (in JavaScript) but I can't seem to find a suitable one yet. I just need it to sort each column alphabetically. It doesn't need to ignore any code or any numbers or to work with currency. Just a click on the column header switches it from sorted a-z/z-a.
Does anyone know of a really simple solution like this?
This question is related to
javascript
sorting
html-table
Nick Grealy's accepted answer is great but acts a bit quirky if your rows are inside a <tbody>
tag (the first row isn't ever sorted and after sorting rows end up outside of the tbody tag, possibly losing formatting).
This is a simple fix, however:
Just change:
document.querySelectorAll('th').forEach(th => th.addEventListener('click', (() => {
const table = th.closest('table');
Array.from(table.querySelectorAll('tr:nth-child(n+2)'))
.sort(comparer(Array.from(th.parentNode.children).indexOf(th), this.asc = !this.asc))
.forEach(tr => table.appendChild(tr) );
to:
document.querySelectorAll('th').forEach(th => th.addEventListener('click', (() => {
const table = th.closest('table');
const tbody = table.querySelector('tbody');
Array.from(tbody.querySelectorAll('tr'))
.sort(comparer(Array.from(th.parentNode.children).indexOf(th), this.asc = !this.asc))
.forEach(tr => tbody.appendChild(tr) );
I have edited the code from one of the example here to use jquery. It's still not 100% jquery though. Any thoughts on the two different versions, like what are the pros and cons of each?
function column_sort() {
getCellValue = (tr, idx) => $(tr).find('td').eq( idx ).text();
comparer = (idx, asc) => (a, b) => ((v1, v2) =>
v1 !== '' && v2 !== '' && !isNaN(v1) && !isNaN(v2) ? v1 - v2 : v1.toString().localeCompare(v2)
)(getCellValue(asc ? a : b, idx), getCellValue(asc ? b : a, idx));
table = $(this).closest('table')[0];
tbody = $(table).find('tbody')[0];
elm = $(this)[0];
children = elm.parentNode.children;
Array.from(tbody.querySelectorAll('tr')).sort( comparer(
Array.from(children).indexOf(elm), table.asc = !table.asc))
.forEach(tr => tbody.appendChild(tr) );
}
table.find('thead th').on('click', column_sort);
<!DOCTYPE html>
<html>
<head>
<style>
table, td, th {
border: 1px solid;
border-collapse: collapse;
}
td , th {
padding: 5px;
width: 100px;
}
th {
background-color: lightgreen;
}
</style>
</head>
<body>
<h2>JavaScript Array Sort</h2>
<p>Click the buttons to sort car objects on age.</p>
<p id="demo"></p>
<script>
var nameArrow = "", yearArrow = "";
var cars = [
{type:"Volvo", year:2016},
{type:"Saab", year:2001},
{type:"BMW", year:2010}
];
yearACS = true;
function sortYear() {
if (yearACS) {
nameArrow = "";
yearArrow = "";
cars.sort(function(a,b) {
return a.year - b.year;
});
yearACS = false;
}else {
nameArrow = "";
yearArrow = "";
cars.sort(function(a,b) {
return b.year - a.year;
});
yearACS = true;
}
displayCars();
}
nameACS = true;
function sortName() {
if (nameACS) {
nameArrow = "";
yearArrow = "";
cars.sort(function(a,b) {
x = a.type.toLowerCase();
y = b.type.toLowerCase();
if (x > y) {return 1;}
if (x < y) {return -1};
return 0;
});
nameACS = false;
} else {
nameArrow = "";
yearArrow = "";
cars.sort(function(a,b) {
x = a.type.toUpperCase();
y = b.type.toUpperCase();
if (x > y) { return -1};
if (x <y) { return 1 };
return 0;
});
nameACS = true;
}
displayCars();
}
displayCars();
function displayCars() {
var txt = "<table><tr><th onclick='sortName()'>name " + nameArrow + "</th><th onclick='sortYear()'>year " + yearArrow + "</th><tr>";
for (let i = 0; i < cars.length; i++) {
txt += "<tr><td>"+ cars[i].type + "</td><td>" + cars[i].year + "</td></tr>";
}
txt += "</table>";
document.getElementById("demo").innerHTML = txt;
}
</script>
</body>
</html>
_x000D_
It does WAY more than "just sorting", but dataTables.net does what you need. I use it daily and is well supported and VERY fast (does require jQuery)
DataTables is a plug-in for the jQuery Javascript library. It is a highly flexible tool, based upon the foundations of progressive enhancement, which will add advanced interaction controls to any HTML table.
Google Visualizations is another option, but requires a bit more setup that dataTables, but does NOT require any particular framework/library (other than google.visualizations):
http://code.google.com/apis/ajax/playground/?type=visualization#table
And there are other options to... especially if you're using one of the other JS frameworks. Dojo, Prototype, etc all have usable "table enhancement" plugins that provide at minimum table sorting functionality. Many provide more, but I'll restate...I've yet to come across one as powerful and as FAST as datatables.net.
In case your table does not have th
s but only td
s (with headers included) you can try the following which is based on Nick Grealy's answer above:
const getCellValue = (tr, idx) => tr.children[idx].innerText || tr.children[idx].textContent;_x000D_
_x000D_
const comparer = (idx, asc) => (a, b) => ((v1, v2) => _x000D_
v1 !== '' && v2 !== '' && !isNaN(v1) && !isNaN(v2) ? v1 - v2 : v1.toString().localeCompare(v2)_x000D_
)(getCellValue(asc ? a : b, idx), getCellValue(asc ? b : a, idx));_x000D_
_x000D_
// do the work..._x000D_
document.querySelectorAll('tr:first-child td').forEach(td => td.addEventListener('click', (() => {_x000D_
const table = td.closest('table');_x000D_
Array.from(table.querySelectorAll('tr:nth-child(n+2)'))_x000D_
.sort(comparer(Array.from(td.parentNode.children).indexOf(td), this.asc = !this.asc))_x000D_
.forEach(tr => table.appendChild(tr) );_x000D_
})));
_x000D_
@charset "UTF-8";_x000D_
@import url('https://fonts.googleapis.com/css?family=Roboto');_x000D_
_x000D_
*{_x000D_
font-family: 'Roboto', sans-serif;_x000D_
text-transform:capitalize;_x000D_
overflow:hidden;_x000D_
margin: 0 auto;_x000D_
text-align:left;_x000D_
}_x000D_
_x000D_
table {_x000D_
color:#666;_x000D_
font-size:12px;_x000D_
background:#124;_x000D_
border:#ccc 1px solid;_x000D_
-moz-border-radius:3px;_x000D_
-webkit-border-radius:3px;_x000D_
border-radius:3px;_x000D_
border-collapse: collapse;_x000D_
width: 100%;_x000D_
}_x000D_
_x000D_
table td {_x000D_
padding:10px;_x000D_
border-top: 1px solid #ffffff;_x000D_
border-bottom:1px solid #e0e0e0;_x000D_
border-left: 1px solid #e0e0e0;_x000D_
background: #fafafa;_x000D_
background: -webkit-gradient(linear, left top, left bottom, from(#fbfbfb), to(#fafafa));_x000D_
background: -moz-linear-gradient(top, #fbfbfb, #fafafa);_x000D_
width: 6.9in;_x000D_
}_x000D_
_x000D_
table tbody tr:first-child td_x000D_
{_x000D_
background: #124!important;_x000D_
color:#fff;_x000D_
}_x000D_
_x000D_
table tbody tr th_x000D_
{_x000D_
padding:10px;_x000D_
border-left: 1px solid #e0e0e0;_x000D_
background: #124!important;_x000D_
color:#fff;_x000D_
}
_x000D_
<table>_x000D_
<tr><td>Country</td><td>Date</td><td>Size</td></tr>_x000D_
<tr><td>France</td><td>2001-01-01</td><td><i>25</i></td></tr>_x000D_
<tr><td>spain</td><td>2005-05-05</td><td></td></tr>_x000D_
<tr><td>Lebanon</td><td>2002-02-02</td><td><b>-17</b></td></tr>_x000D_
<tr><td>Argentina</td><td>2005-04-04</td><td>100</td></tr>_x000D_
<tr><td>USA</td><td></td><td>-6</td></tr>_x000D_
</table>
_x000D_
The best way I know to sort HTML table with javascript is with the following function.
Just pass to it the id of the table you'd like to sort and the column number on the row. it assumes that the column you are sorting is numeric or has numbers in it and will do regex replace to get the number itself (great for currencies and other numbers with symbols in it).
function sortTable(table_id, sortColumn){
var tableData = document.getElementById(table_id).getElementsByTagName('tbody').item(0);
var rowData = tableData.getElementsByTagName('tr');
for(var i = 0; i < rowData.length - 1; i++){
for(var j = 0; j < rowData.length - (i + 1); j++){
if(Number(rowData.item(j).getElementsByTagName('td').item(sortColumn).innerHTML.replace(/[^0-9\.]+/g, "")) < Number(rowData.item(j+1).getElementsByTagName('td').item(sortColumn).innerHTML.replace(/[^0-9\.]+/g, ""))){
tableData.insertBefore(rowData.item(j+1),rowData.item(j));
}
}
}
}
Using example:
$(function(){
// pass the id and the <td> place you want to sort by (td counts from 0)
sortTable('table_id', 3);
});
I wrote up some code that will sort a table by a row, assuming only one <tbody>
and cells don't have a colspan.
function sortTable(table, col, reverse) {
var tb = table.tBodies[0], // use `<tbody>` to ignore `<thead>` and `<tfoot>` rows
tr = Array.prototype.slice.call(tb.rows, 0), // put rows into array
i;
reverse = -((+reverse) || -1);
tr = tr.sort(function (a, b) { // sort rows
return reverse // `-1 *` if want opposite order
* (a.cells[col].textContent.trim() // using `.textContent.trim()` for test
.localeCompare(b.cells[col].textContent.trim())
);
});
for(i = 0; i < tr.length; ++i) tb.appendChild(tr[i]); // append each row in order
}
// sortTable(tableNode, columId, false);
If you don't want to make the assumptions above, you'd need to consider how you want to behave in each circumstance. (e.g. put everything into one <tbody>
or add up all the preceeding colspan values, etc.)
You could then attach this to each of your tables, e.g. assuming titles are in <thead>
function makeSortable(table) {
var th = table.tHead, i;
th && (th = th.rows[0]) && (th = th.cells);
if (th) i = th.length;
else return; // if no `<thead>` then do nothing
while (--i >= 0) (function (i) {
var dir = 1;
th[i].addEventListener('click', function () {sortTable(table, i, (dir = 1 - dir))});
}(i));
}
function makeAllSortable(parent) {
parent = parent || document.body;
var t = parent.getElementsByTagName('table'), i = t.length;
while (--i >= 0) makeSortable(t[i]);
}
and then invoking makeAllSortable
onload.
Example fiddle of it working on a table.
You could deal with a json array and the sort
function. It is a pretty easy maintanable structure to manipulate (ex: sorting).
Untested, but here's the idea. That would support multiple ordering and sequential ordering if you pass in a array in which you put the columns in the order they should be ordered by.
var DATA_TABLE = {
{name: 'George', lastname: 'Blarr', age:45},
{name: 'Bob', lastname: 'Arr', age: 20}
//...
};
function sortDataTable(arrayColNames, asc) { // if not asc, desc
for (var i=0;i<arrayColNames.length;i++) {
var columnName = arrayColNames[i];
DATA_TABLE = DATA_TABLE.sort(function(a,b){
if (asc) {
return (a[columnName] > b[columnName]) ? 1 : -1;
} else {
return (a[columnName] < b[columnName]) ? 1 : -1;
}
});
}
}
function updateHTMLTable() {
// update innerHTML / textContent according to DATA_TABLE
// Note: textContent for firefox, innerHTML for others
}
Now let's imagine you need to order by lastname, then name, and finally by age.
var orderAsc = true;
sortDataTable(['lastname', 'name', 'age'], orderAsc);
It should result in something like :
{name: 'Jack', lastname: 'Ahrl', age: 20},
{name: 'Jack', lastname: 'Ahrl', age: 22},
//...
Sorting html table column on page load
var table = $('table#all_items_table');
var rows = table.find('tr:gt(0)').toArray().sort(comparer(3));
for (var i = 0; i < rows.length; i++) {
table.append(rows[i])
}
function comparer(index) {
return function (a, b) {
var v1= getCellValue(a, index),
v2= getCellValue(b, index);
return $.isNumeric(v2) && $.isNumeric(v1) ? v2 - v1: v2.localeCompare(v1)
}
}
function getCellValue(row, index) {
return parseFloat($(row).children('td').eq(index).html().replace(/,/g,'')); //1234234.45645->1234234
}
Here is a complete example using pure JavaScript. The algorithm used for sorting is basically BubbleSort. Here is a Fiddle.
<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="UTF-8">
<script type="text/javascript">
function sort(ascending, columnClassName, tableId) {
var tbody = document.getElementById(tableId).getElementsByTagName(
"tbody")[0];
var rows = tbody.getElementsByTagName("tr");
var unsorted = true;
while (unsorted) {
unsorted = false
for (var r = 0; r < rows.length - 1; r++) {
var row = rows[r];
var nextRow = rows[r + 1];
var value = row.getElementsByClassName(columnClassName)[0].innerHTML;
var nextValue = nextRow.getElementsByClassName(columnClassName)[0].innerHTML;
value = value.replace(',', '.'); // in case a comma is used in float number
nextValue = nextValue.replace(',', '.');
if (!isNaN(value)) {
value = parseFloat(value);
nextValue = parseFloat(nextValue);
}
if (ascending ? value > nextValue : value < nextValue) {
tbody.insertBefore(nextRow, row);
unsorted = true;
}
}
}
};
</script>
</head>
<body>
<table id="content-table">
<thead>
<tr>
<th class="id">ID <a
href="javascript:sort(true, 'id', 'content-table');">asc</a> <a
href="javascript:sort(false, 'id', 'content-table');">des</a>
</th>
<th class="country">Country <a
href="javascript:sort(true, 'country', 'content-table');">asc</a> <a
href="javascript:sort(false, 'country', 'content-table');">des</a>
</th>
<th class="some-fact">Some fact <a
href="javascript:sort(true, 'some-fact', 'content-table');">asc</a>
<a href="javascript:sort(false, 'some-fact', 'content-table');">des</a>
<th>
</tr>
</thead>
<tbody>
<tr>
<td class="id">001</td>
<td class="country">Germany</td>
<td class="some-fact">16.405</td>
</tr>
<tr>
<td class="id">002</td>
<td class="country">France</td>
<td class="some-fact">10.625</td>
</tr>
<tr>
<td class="id">003</td>
<td class="country">UK</td>
<td class="some-fact">15.04</td>
</tr>
<tr>
<td class="id">004</td>
<td class="country">China</td>
<td class="some-fact">13.536</td>
</tr>
</tbody>
</table>
</body>
</html>
You can also check out the source from here: https://github.com/wmentzel/table-sort
Another approach to sort HTML table. (based on W3.JS HTML Sort)
var collection = [{_x000D_
"Country": "France",_x000D_
"Date": "2001-01-01",_x000D_
"Size": "25",_x000D_
}, {_x000D_
"Country": "spain",_x000D_
"Date": "2005-05-05",_x000D_
"Size": "",_x000D_
}, {_x000D_
"Country": "Lebanon",_x000D_
"Date": "2002-02-02",_x000D_
"Size": "-17",_x000D_
}, {_x000D_
"Country": "Argentina",_x000D_
"Date": "2005-04-04",_x000D_
"Size": "100",_x000D_
}, {_x000D_
"Country": "USA",_x000D_
"Date": "",_x000D_
"Size": "-6",_x000D_
}]_x000D_
_x000D_
for (var j = 0; j < 3; j++) {_x000D_
$("#myTable th:eq(" + j + ")").addClass("control-label clickable");_x000D_
$("#myTable th:eq(" + j + ")").attr('onClick', "w3.sortHTML('#myTable', '.item', 'td:nth-child(" + (j + 1) + ")')");_x000D_
}_x000D_
_x000D_
$tbody = $("#myTable").append('<tbody></tbody>');_x000D_
_x000D_
for (var i = 0; i < collection.length; i++) {_x000D_
$tbody = $tbody.append('<tr class="item"><td>' + collection[i]["Country"] + '</td><td>' + collection[i]["Date"] + '</td><td>' + collection[i]["Size"] + '</td></tr>');_x000D_
}
_x000D_
.control-label:after {_x000D_
content: "*";_x000D_
color: red;_x000D_
}_x000D_
_x000D_
.clickable {_x000D_
cursor: pointer;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://www.w3schools.com/lib/w3.js"></script>_x000D_
<link href="https://www.w3schools.com/w3css/4/w3.css" rel="stylesheet" />_x000D_
<p>Click the <strong>table headers</strong> to sort the table accordingly:</p>_x000D_
_x000D_
<table id="myTable" class="w3-table-all">_x000D_
<thead>_x000D_
<tr>_x000D_
<th>Country</th>_x000D_
<th>Date</th>_x000D_
<th>Size</th>_x000D_
</tr>_x000D_
</thead>_x000D_
</table>
_x000D_
Sorting table rows by cell. 1. Little simpler and has some features. 2. Distinguish 'number' and 'string' on sorting 3. Add toggle to sort by ASC, DESC
var index; // cell index
var toggleBool; // sorting asc, desc
function sorting(tbody, index){
this.index = index;
if(toggleBool){
toggleBool = false;
}else{
toggleBool = true;
}
var datas= new Array();
var tbodyLength = tbody.rows.length;
for(var i=0; i<tbodyLength; i++){
datas[i] = tbody.rows[i];
}
// sort by cell[index]
datas.sort(compareCells);
for(var i=0; i<tbody.rows.length; i++){
// rearrange table rows by sorted rows
tbody.appendChild(datas[i]);
}
}
function compareCells(a,b) {
var aVal = a.cells[index].innerText;
var bVal = b.cells[index].innerText;
aVal = aVal.replace(/\,/g, '');
bVal = bVal.replace(/\,/g, '');
if(toggleBool){
var temp = aVal;
aVal = bVal;
bVal = temp;
}
if(aVal.match(/^[0-9]+$/) && bVal.match(/^[0-9]+$/)){
return parseFloat(aVal) - parseFloat(bVal);
}
else{
if (aVal < bVal){
return -1;
}else if (aVal > bVal){
return 1;
}else{
return 0;
}
}
}
below is html sample
<table summary="Pioneer">
<thead>
<tr>
<th scope="col" onclick="sorting(tbody01, 0)">No.</th>
<th scope="col" onclick="sorting(tbody01, 1)">Name</th>
<th scope="col" onclick="sorting(tbody01, 2)">Belong</th>
<th scope="col" onclick="sorting(tbody01, 3)">Current Networth</th>
<th scope="col" onclick="sorting(tbody01, 4)">BirthDay</th>
<th scope="col" onclick="sorting(tbody01, 5)">Just Number</th>
</tr>
</thead>
<tbody id="tbody01">
<tr>
<td>1</td>
<td>Gwanshic Yi</td>
<td>Gwanshic Home</td>
<td>120000</td>
<td>1982-03-20</td>
<td>124,124,523</td>
</tr>
<tr>
<td>2</td>
<td>Steve Jobs</td>
<td>Apple</td>
<td>19000000000</td>
<td>1955-02-24</td>
<td>194,523</td>
</tr>
<tr>
<td>3</td>
<td>Bill Gates</td>
<td>MicroSoft</td>
<td>84300000000</td>
<td>1955-10-28</td>
<td>1,524,124,523</td>
</tr>
<tr>
<td>4</td>
<td>Larry Page</td>
<td>Google</td>
<td>39100000000</td>
<td>1973-03-26</td>
<td>11,124,523</td>
</tr>
</tbody>
</table>
Source: Stackoverflow.com