We are required to write a JavaScript function that takes in an array of objects of dates like this −
const arr = [ {date: "2016-06-08 18:10:00"}, {date: "2016-04-26 20:01:00"}, {date: "2017-02-06 14:38:00"}, {date: "2017-01-18 17:30:21"}, {date: "2017-01-18 17:24:00"} ];
We are required to write a JavaScript function that takes in one such array. The function should then sort the array according to the date property of the objects.
Example
const arr = [ {date: "2016-06-08 18:10:00"}, {date: "2016-04-26 20:01:00"}, {date: "2017-02-06 14:38:00"}, {date: "2017-01-18 17:30:21"}, {date: "2017-01-18 17:24:00"} ]; const sortByTime = (arr = []) => { arr.sort((a, b) => { const dateA = new Date( a.date ); const dateB = new Date( b.date ); return dateA < dateB ? -1 : ( dateA > dateB ? 1 : 0); }); }; sortByTime(arr); console.log(arr);
Output
And the output in the console will be −
[ { date: '2016-04-26 20:01:00' }, { date: '2016-06-08 18:10:00' }, { date: '2017-01-18 17:24:00' }, { date: '2017-01-18 17:30:21' }, { date: '2017-02-06 14:38:00' } ]