
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Sort Nested Array of Objects by Date in JavaScript
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' } ] }
Advertisements