猿问

在推送到数组时对项目进行排序

我想在将项目推送到数组时对日期和时间进行排序。到目前为止,我只能对日期进行排序,但无法对时间进行排序。如果同一日期有两次,那么如何先对日期进行排序,然后再对该日期的时间进行排序。


let items = [

{'id': 'id7', 'date': '2020-08-17', 'time': '05:02:54.000'},

{'id': 'id2', 'date': '2020-05-12', 'time': '02:09:57.000'}, 

{'id': 'id3', 'date': '2020-05-12', 'time': '03:04:44.000'}, //both the 2020-05-12 date has two timings so I want to sort these time too along with the date

{'id': 'id4', 'date': '2020-09-23', 'time': '07:16:23.000'}

];


const headers = [

'ID',

'Date',

'Time'

];


dataArr = []


items.forEach(item => {

    dataArr.push([

        item.id,

        item.date,

        item.time

    ]);

})

;

let sortedData = [headers, ...dataArr.sort((a, b) => a[1].localeCompare(b[1]))];

最终排序的数组必须看起来像



['id': 'id2', 'date': '2020-05-12', 'time': '02:09:57.000'], 

['id': 'id3', 'date': '2020-05-12', 'time': '03:04:44.000'],

['id': 'id7', 'date': '2020-08-17', 'time': '05:02:54.000'],

['id': 'id4', 'date': '2020-09-23', 'time': '07:16:23.000']


开心每一天1111
浏览 110回答 3
3回答

幕布斯7119047

你可以尝试这样的事情:function compare (a,b) {&nbsp; &nbsp; if(a<b) return -1;&nbsp; &nbsp; else if(a>b) return 1;&nbsp; &nbsp; else return 0;}items.sort((a,b) => {&nbsp; &nbsp; let d = compare(a.date, b.date);&nbsp; &nbsp; if(d < 0) return -1;&nbsp; &nbsp; else if(d > 0) return 1;&nbsp; &nbsp; else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;//Same date compare time&nbsp; &nbsp; &nbsp; &nbsp; let t = compare(a.time, b.time);&nbsp; &nbsp; &nbsp; &nbsp; if(t < 0) return -1;&nbsp; &nbsp; &nbsp; &nbsp; else if(t > 0) return 1;&nbsp; &nbsp; &nbsp; &nbsp; else return 0;&nbsp; &nbsp; }});这首先比较日期。如果日期不同,则无需比较时间。如果日期相同,您可以比较时间。

12345678_0001

let sortedData = [headers, ...dataArr.sort((a, b) => a[1].localeCompare(b[1])==0 ? a[2].localeCompare(b[2]) : a[1].localeCompare(b[1]))];let items = [{'id': 'id7', 'date': '2020-08-17', 'time': '05:02:54.000'},&nbsp;{'id': 'id3', 'date': '2020-05-12', 'time': '03:04:44.000'},{'id': 'id4', 'date': '2020-09-23', 'time': '07:16:23.000'},{'id': 'id2', 'date': '2020-05-12', 'time': '02:09:57.000'}];const headers = ['ID','Date','Time'];dataArr = []items.forEach(item => {&nbsp; &nbsp; dataArr.push([&nbsp; &nbsp; &nbsp; &nbsp; item.id,&nbsp; &nbsp; &nbsp; &nbsp; item.date,&nbsp; &nbsp; &nbsp; &nbsp; item.time&nbsp; &nbsp; ]);});let sortedData = [headers, ...dataArr.sort((a, b) => a[1].localeCompare(b[1])==0 ? a[2].localeCompare(b[2]) : a[1].localeCompare(b[1]))];console.log(sortedData)

慕桂英3389331

尝试在单个排序函数中对日期和时间进行排序let ss = [{'id': 'id7', 'date': '2020-08-17', 'time': '05:02:54.000'},{'id': 'id2', 'date': '2020-05-12', 'time': '02:09:57.000'},&nbsp;{'id': 'id3', 'date': '2020-05-12', 'time': '03:04:44.000'},&nbsp;{'id': 'id4', 'date': '2020-09-23', 'time': '07:16:23.000'}];let dd = ss.sort((a,b)=>new Date(a.date+':'+a.time) - new Date(b.date+':'+b.time))console.log(dd)
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答