I have generic data that I built html table from it using Javascript only like this:
HTML:
<div id="container"></div>
Javascript:
var dataset = [ { "field1":"val1", "field2":"val2", "field3":"val3" }, { "field1":"val4", "field2":"val5", "field3":"val6", "field4":"val7" } ] ;
function addHeaders(table, keys) {
var row = table.insertRow();
for( var i = 0; i < keys.length; i++ ) {
var cell = row.insertCell();
cell.appendChild(document.createTextNode(keys[i]));
}
}
var max_keys = 0;
var max_idx = 0;
for( var i = 0; i < dataset.length; i++ ) {
var child = dataset[i];
cur_keys = Object.keys(child).length;
if (cur_keys > max_keys) {
max_keys = cur_keys;
max_idx = i;
}
}
var table = document.createElement('table');
addHeaders(table, Object.keys(dataset[max_idx]));
for( var i = 0; i < dataset.length; i++ ) {
var child = dataset[i];
var row = table.insertRow();
Object.keys(child).forEach(function(k) {
var cell = row.insertCell();
cell.appendChild(document.createTextNode(child[k]));
})
}
document.getElementById('container').appendChild(table);
How I can allow user to sort the columns ascending and descending ?
update: sorting code work for strings but not for numeric !!
dataset.sort(function (a, b) {
var nameA = Number(a.field2);
var nameB = Number(b.field2);
return (nameA - nameB);
});
I would sort the dataset beforehand (
dataset.sort(...)
), and recreate the table rows everytime the sorting order (and dataset) changes.Or use something that gives this already done for you like Bootstrap tables.
Bootstrap - How to sort table columns
Edit:
Sorting with pure JavaScript:
Asc (field1):
dataset.sort((a,b) => a.field1 - b.field1)
Desc (field1):
dataset.sort((a,b) => b.field1 - a.field1)
Edit2:
If you are working with string, remember to cast them to
Number
first:dataset.sort((a,b) => Number(a.field1) - Number(b.field1))