如何对javascript表进行排序(升序或降序),该表是某些SQL操作表的结果

How to sort a javascript table (ascending or descending) which is the result of some SQL operated table?

本文关键字:SQL 结果 操作表 javascript 排序 升序 降序      更新时间:2024-06-26

我使用JavaScript创建了一个表,其中有三列Event ID、Events和Total Count。现在我必须按降序对第三列,即总计数进行排序。我一直在网上寻找如何排序。我知道如何对标准HTML表("order": [[ 2, "desc" ]])的表进行排序,但这个表是用JavaScript形成的,所以我很困惑。我可以使用循环反向创建表,即for(var i=to; i>=from; i--),但我的结果JS表是从SQL生成的表中得到的结果,其中"事件"不是按升序或降序排列的。换句话说,我正在从SQL生成的表创建这个JavaScript表。以下是我正在处理的代码:

<script>
    $(function() {
        CreateTable(GetSum('#displaytable'));
    });
    function GetSum(tableIdWithHash) {
        var Sum = [];
        var EventIds = [];
        var EventName = [];
        var Data = [];
        $(tableIdWithHash).find('.eventCounts').each(function(i){
        var Counte = $(this).html();
        var Ide = $(this).siblings('.Idevent').html();
        var eName = $(this).siblings('.eventNames').html();
            allSum.sort(function(a,b){
      if(a.eCount > b.eCount){
         return 1;
      } else if (a.eCount < b.eCount){
         return -1;
      } else{
         return 0;
      }
    }); 
        if (EventIds.indexOf(Ide) === -1) {
            EventIds.push(Ide);
            EventName.push(eName);
        }
        var index = EventIds.indexOf(Ide);
        if (Sum[index] == undefined) {
            Sum[index] = Number(Counte);
        }
        else {
            Sum[index] += Number(Counte);
        }
        });
        Data.push(EventIds);
        Data.push(EventName);
        Data.push(Sum);
        //"order": [[ 2, "desc" ]]
        return Data;
    }       
</script>

我没有在问题中看到您的实际数据,所以我会假设它看起来像这样:

var data = [{eventId:1, eventName:'Fish fry', totalCount:5},...]; // where the ... indicates more records of that shape

好的,考虑到这种结构,在将数据写入表之前,可以使用Array.prototype.sort()对数据进行排序:

data.sort(function(a,b){
  if(a.totalCount > b.totalCount){
     return 1;
  } else if (a.totalCount < b.totalCount{
     return -1;
  } else{
     return 0;
  }
});