javascript - 按日期顺序对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);
})
我敢肯定,这很明显,但谁能指出我哪里出错以及如何正确排序?
解决方案
接收get 2个参数的函数sort
,每个参数都是一个obj,所以你可以访问它的属性。
像这样的东西应该工作:
arr.sort((a, b) => {
return a.event_end > b.event_end ? -1 : 1;
})
推荐阅读
- c# - 如何强制 Visual Studio 2022 创建带有命名空间和类的控制台项目(就像过去的好日子一样)?
- flutter - 我们可以与从事同一项目的其他开发人员共享我的“API KEY”吗?
- c - Windows API:可以以编程方式移动 Windows IME 输入框吗?
- multilingual - 如何削减 Huggingface 上共享的预训练多语言模型?
- css - 未检测到 xpath 跨度
- batch-file - 批处理文件从另一个文件的文件中添加一列,第一个字段匹配,第二个文件具有大列
- terraform - 在 oci 中获取子网值时出现 Terraform 错误
- flutter - 如何在 id 匹配的颤振中显示列表
- angular - 节点伪造 AES 数据解密不返回原始数据。角/打字稿
- apache-spark - Spark SQL中的多列分区无法正常工作