gpt4 book ai didi

javascript - 按日期顺序对nodejs中的数组进行排序(从最近到最旧)

转载 作者:行者123 更新时间:2023-11-28 03:09:12 26 4
gpt4 key购买 nike

我正在尝试对以下数组进行排序,以便最新的 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);
})

我确信这很明显,但有人能指出我出错的方向以及如何正确排序吗?

最佳答案

var obj = {
"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"
}
]
}

obj.results.sort((a, b) => {
return new Date(b.event_end) - new Date(a.event_end)
})

console.log(obj.results)

关于javascript - 按日期顺序对nodejs中的数组进行排序(从最近到最旧),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60310434/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com