将数组放入HTML表并升序或降序

时间:2017-11-25 02:19:13

标签: javascript jquery html sorting

我正在尝试在页面加载时将JavaScript数组放入HTML表格中,然后当单击箭头(向上或向下)时,它会将它们按升序或降序排列。

这是我的脚本:

df = data.frame(species_id = c("BROC","broc"),count = c(16,7))

以下是我的一点点HTML:

# A tibble: 1 x 2
  species_id total
       <chr> <dbl>
1       broc    23

我知道这很简单,但我很难过。同样,我正在尝试在页面加载时将数组加载到HTML表格中,然后当您单击向上箭头或向下箭头时,表格会按升序或降序排列。

1 个答案:

答案 0 :(得分:0)

排序数据

您可以使用数组Sort函数来升序和降序数据(对象数组),例如,

/** 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 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 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;
    }
}

完整演示位于JsFiddle

相关问题