在 JavaScript 中按日期升序和降序对包含对象的嵌套数组进行排序
javascriptweb developmentfront end technologyobject oriented programming
假设我们有一个 JSON 对象,其中包含类似这样的嵌套数组 −
const arr = { "DATA": [ { "BookingID": "9513", "DutyStart": "2016-02-11 12:00:00" }, { &"BookingID":"91157307", &"DutyStart":"2016-02-11 13:00:00" }, { &"BookingID":"95117317", "DutyStart":"2016-02-11 13:30:00" }, { "BookingID":"957266", "DutyStart":"2016-02-12 19:15:00" }, { &"BookingID": &"74", &"DutyStart": &"2016-02-11 12:21:00" } ] };
我们需要编写一个 JavaScript 函数,该函数接受一个这样的对象,并根据 'dutyStart' 属性按升序或降序对嵌套数组进行排序。
示例
其代码为 −
const arr = { "DATA": [ { "BookingID": "9513", "DutyStart": "2016-02-11 12:00:00" }, { "BookingID": "91157307", "DutyStart": "2016-02-11 13:00:00" }, { "BookingID": "95117317", "DutyStart": "2016-02-11 13:30:00" }, { "BookingID": "957266", "DutyStart": "2016-02-12 19:15:00" }, { "BookingID": "74", "DutyStart": "2016-02-11 12:21:00" } ] }; const sortByDate = arr => { const sorter = (a, b) => { return new Date(a.DutyStart).getTime() - new Date(b.DutyStart).getTime(); }; arr["DATA"].sort(sorter); return arr; }; console.log(sortByDate(arr));
输出
控制台中的输出将是 −
{ DATA: [ { BookingID: '9513', DutyStart: '2016-02-11 12:00:00' }, { BookingID: '74', DutyStart: '2016-02-11 12:21:00' }, { BookingID: '91157307', DutyStart: '2016-02-11 13:00:00' }, { BookingID: '95117317', DutyStart: '2016-02-11 13:30:00' }, { BookingID: '957266', DutyStart: '2016-02-12 19:15:00' } ] }