我有一系列具有“时间”和“投票”的对象 我希望按时间升序排序。请问我该怎么办?
[ { time: '10:00 - 11:00', vote: 0 },
{ time: '7:00 - 8:00', vote: 2 },
{ time: '12:00 - 1:00', vote: 0 },
{ time: '11:00 - 12:00', vote: 2 },
{ time: '4:00 - 5:00', vote: 0 },
{ time: '2:00 - 3:00', vote: 0 },
{ time: '5:00 - 6:00', vote: 0 },
{ time: '9:00 - 10:00', vote: 2 },
{ time: '8:00 - 9:00', vote: 1 },
{ time: '1:00 - 2:00', vote: 1 },
{ time: '3:00 - 4:00', vote: 0 } ]
答案 0 :(得分:0)
您可以使用string#localeCompare
对时间进行排序。
let data = [ { time: '10:00 - 11:00', vote: 0 }, { time: '7:00 - 8:00', vote: 2 }, { time: '12:00 - 1:00', vote: 0 }, { time: '11:00 - 12:00', vote: 2 }, { time: '4:00 - 5:00', vote: 0 }, { time: '2:00 - 3:00', vote: 0 }, { time: '5:00 - 6:00', vote: 0 }, { time:'9:00 - 10:00', vote: 2 }, { time: '8:00 - 9:00', vote: 1 }, { time: '1:00 - 2:00', vote: 1 }, { time: '3:00 - 4:00', vote: 0 } ];
data.sort((a,b) => a.time.localeCompare(b.time, undefined, {numeric:true}));
console.log(data);
let data = [ { time: '10:00 - 11:00', vote: 0 }, { time: '7:00 - 8:00', vote: 2 }, { time: '12:00 - 1:00', vote: 0 }, { time: '11:00 - 12:00', vote: 2 }, { time: '4:00 - 5:00', vote: 0 }, { time: '2:00 - 3:00', vote: 0 }, { time: '5:00 - 6:00', vote: 0 }, { time:'9:00 - 10:00', vote: 2 }, { time: '8:00 - 9:00', vote: 1 }, { time: '1:00 - 2:00', vote: 1 }, { time: '3:00 - 4:00', vote: 0 } ],
result = data.map(({time},i) => [new Date('1970/01/01 ' + time.split(" - ")[0]), i])
.sort((a,b) => a[0] - b[0])
.map(([,index]) => data[index]);
console.log(result);