首页 > 解决方案 > 按日期顺序对nodejs中的数组进行排序(从最近到最旧)

问题描述

我正在尝试对以下数组进行排序,以便最近的 event_end 排在第一位

{
   "results":[
      {
         "event_start":"2017-11-27T09:00:00Z",
         "event_end":"2017-11-27T09:00:00Z",
         "attendance":0,
         "title":"Administrate Training Session",
         "type":"delegate"
      },
      {
         "event_start":"2018-02-01T09:00:00Z",
         "event_end":"2018-02-01T09:00:00Z",
         "attendance":0,
         "title":"Health and Safety Awareness (HSA)",
         "type":"delegate"
      },
      {
         "event_start":"2018-02-19T09:00:00Z",
         "event_end":"2018-04-30T09:00:00Z",
         "attendance":0,
         "title":"SMSTS",
         "type":"delegate"
      }
   ]
}

我当前的代码(这是在尝试了几乎所有不同的方法之后):

Array.from(outcome).sort(sortFunction);
      function sortFunction(a, b){
        if(b[3] === a[3]){
          return 0;
        } else {
          return (b[3] < a[3]) ? -1 : 1;
        }
      }

并且只是为了清楚地说明数组是如何创建的:

var history = JSON.parse(body);
      var outcome = {};
      var key = 'results';
      outcome[key] = [];
      history.forEach(delegate => {
          var data = null;
          var sessionKey;
          var attendanceCount = 0;
          var sessionCount = 0;   
          var attended = 0;    
          Array.from(delegate['session_attendance']).forEach(function(val){
            if(!val.__proto__.__proto__){
              sessionCount++;
            }
          });      
          var type;              
          for(var k in delegate['session_attendance']){
            sessionKey = k;
            if(k['status'] == true){
              attendanceCount++;
            }
          }
          if(attendanceCount == 0){
            attended = attendanceCount;
          } else {
            (attendanceCount / sessionCount) * 100
          }
          if(delegate['registration']['booking_contact'] !== null){
            if(delegate['registration']['booking_contact']['id'] == delegate['contact']['id']){
              type = 'booking_contact';
            } 
          } else{
            type = 'delegate';
          }
          data = {
            'objectId': delegate['id'],                
            'title': delegate['event']['title'],
            'event_start': delegate['event']['start'],
            'event_end': delegate['session_attendance'][sessionKey]['start'],
            'attendance': attended,
            'type': type
          }
          outcome[key].push(data);
        })

我敢肯定,这很明显,但谁能指出我哪里出错以及如何正确排序?

标签: javascriptarrayssorting

解决方案


接收get 2个参数的函数sort,每个参数都是一个obj,所以你可以访问它的属性。

像这样的东西应该工作:

arr.sort((a, b) => {
    return a.event_end > b.event_end ? -1 : 1;
})


推荐阅读