我正在使用React和redux为我的应用程序构建“约会时间表”功能。在这一点上,我正在接收对象数组,其中每个对象代表一个具有属性“ date”和“ startTime”的约会。我的问题是如何按日期和时间对数组进行排序,以便更快地进行约会?
这里是我的简化器(upcomingAppointments是我存储数组的变量):
case 'SCHEDULE_APT_SUCCESS':
//console.log('actions payload: ', action.payload )
return {
...state,
isSchedulingApt: false,
newlyAddedApt: action.payload,
aptScheduleDone: true,
upcomingAppointments: [...state.upcomingAppointments, action.payload]
};
提前感谢。
假设您的数组看起来像这样:
const upcomingAppointments = [
{ date: 'Wed Jun 03 2020', time: '11:39:04' },
{ date: 'Tue Jun 02 2020', time: '16:03:04' },
{ date: 'Wed Jun 03 2020', time: '17:59:12' },
// ...
];
使用Array.prototype.sort(),您可以提供自定义排序功能作为参数:
const sortedAppointments = upcomingAppointments.sort((a, b) => {
const dateA = Date.parse(a.date + ' ' + a.time);
const dateB = Date.parse(b.date + ' ' + b.time);
// Sort in descending order
return dateA < dateB ? 1 : -1;
});