Putting Array Into An Html Table And Ascending Or Descending Them
I'm trying to get a JavaScript array into an HTML table when the page loads, and then when an arrow is clicked (either up or down) it arranges them into ascending or descending ord
Solution 1:
Sorting Data
You can use the array Sort function to ascending and descending your data(array of objects), something like,
/** Sorting the data in asscending by comparing month **/functioninOrderAsc(a, b){
return a.Month == b.Month ? 0 : +(a.Month > b.Month) || -1;
}
/** Sorting the data in descending by comparing month **/functioninOrderDesc(a, b){
return a.Month == b.Month ? 0 : +(a.Month < b.Month) || -1;
}
functionaccending(objs){
return objs.sort(inOrderAsc);
}
functiondescending(objs){
return objs.sort(inOrderDesc);
}
Attach the event
Attach the key down event, on which the sort operation will be performed,
/**Attach event, on which the sort action will be performed **/
document.onkeydown = initEvent;
function initEvent(e) {
e = e || window.event;
if (e.keyCode == '38') {
var result = accending(lakeData);
displayData( result);
} elseif (e.keyCode == '40') {
var result = descending(lakeData);
displayData(result);
}
}
Display data
Now finally display the data after sorting,
/** Display the data in table **/functiondisplayData(objs){
var row, cell, cell2;
var tbody = document.querySelector('#lake tbody');
var cloneTbody = tbody.cloneNode(false);
tbody.parentNode.replaceChild(cloneTbody, tbody);
for(var i=0; i<objs.length; i++){
row = cloneTbody.insertRow();
cell = row.insertCell();
cell.innerHTML = objs[i].Month;
cell2 = row.insertCell();
cell2.innerHTML = objs[i].LakeErieLevels;
}
}
The full demo is on JsFiddle.
Post a Comment for "Putting Array Into An Html Table And Ascending Or Descending Them"