我们需要编写一个JavaScript函数,该函数接受像这样的日期对象数组:
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"} ];
我们需要编写一个包含一个这样的数组的JavaScript函数。然后,该函数应根据对象的date属性对数组进行排序。
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);
输出结果
控制台中的输出将是-
[ { 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' } ]