Suppose we have a JSON Object that contains a nested array like this −
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" } ] };
We are required to write a JavaScript function that takes in one such object and sort the nested array according to the 'dutyStart' property in either ascending or descending order.
Example
The code for this will be −
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));
Output
And the output in the console will be −
{ 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' } ] }