按日期升序降序排序包含对象的嵌套数组(JavaScript)
假设我们有一个包含如下所示嵌套数组的 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' } ] }
广告