Putting array into an HTML table and ascending or descending them

前端 未结 1 1587
礼貌的吻别
礼貌的吻别 2020-12-22 13:42

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 descen

相关标签:
1条回答
  • 2020-12-22 13:56

    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 **/
    function inOrderAsc(a, b){
      return a.Month == b.Month ? 0 : +(a.Month > b.Month) || -1;
    }
    
    /** Sorting the data in descending by comparing month **/
    function inOrderDesc(a, b){
      return a.Month == b.Month ? 0 : +(a.Month < b.Month) || -1;
    }
    
    function accending(objs){
        return objs.sort(inOrderAsc);
     }
    
    function descending(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);
        } else if (e.keyCode == '40') {
            var result = descending(lakeData);
            displayData(result);
        }
    }
    

    Display data

    Now finally display the data after sorting,

    /** Display the data in table **/
    function displayData(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.

    0 讨论(0)
提交回复
热议问题