gpt4 book ai didi

javascript - 如何在不使用 sort 方法的情况下按日期对数组中的对象进行排序?

转载 作者:行者123 更新时间:2023-12-01 00:11:07 24 4
gpt4 key购买 nike

对于我必须为学校做的一个项目,我必须制作一个可以按日期和时间对约会进行排序的应用程序。我有一个包含对象的数组,但无法弄清楚如何按日期对其进行排序,因为日期是嵌套的。

这是我制作的冒泡排序函数:

function bubbleSort() {
const loop = listOfAppointments.length;

for(let i = 0; i < loop; i++) {
for(let j = 0; j < loop; j++) {
if(listOfAppointments[j] > listOfAppointments[j+1]) {
let temp = listOfAppointments[j];
listOfAppointments[j] = listOfAppointments[j+1];
listOfAppointments[j+1] = temp;
}
}
}
}

此函数可以很好地处理数字,但我不知道如何使用此函数对对象进行排序。我知道javascript中有一个排序函数,但我们不允许使用它。我尝试排序的数组如下所示:

[
{
"Appointment": {
"Id": 2,
"nameCustomer": "Henk Jan",
"addresdCustomer": "somethingstreet 34, middleofnowhere",
"time": "2020-01-07T10:00:00Z",
"reason": "gibberish"
}
},
{
"Appointment": {
"Id": 1,
"nameCustomer": "Jan Jaap",
"addresdCustomer": "somethingpavilion 54, middleofnowhere",
"time": "2020-01-07T12:15:00Z",
"reason": "gibberish"
}
},
{
"Appointment": {
"Id": 3,
"nameCustomer": "So Lost",
"addresdCustomer": "somethingthere 234, middleofnowhere",
"time": "2020-01-07T11:30:00Z",
"reason": "gibberish"
}
},
...
]

谢谢!

最佳答案

试试这个

function bubbleSort() {
const loop = listOfAppointments.length;

for(let i = 0; i < loop; i++) {
for(let j = i+1; j < loop; j++) {
if(new Date(listOfAppointments[i].Appointment.time) > new Date(listOfAppointments[j].Appointment.time)) {
let temp = listOfAppointments[i];
listOfAppointments[i] = listOfAppointments[j];
listOfAppointments[j] = temp;
}
}
}

}

关于javascript - 如何在不使用 sort 方法的情况下按日期对数组中的对象进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60061681/

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