简体   繁体   中英

Please How do I sort range of time in ascending order?

I have an array of objects that has "time" and "vote" I wish to sort the time in an ascending order. Please how do I go about this?

[ { 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 } ]

You can use string#localeCompare to sort your time.

 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); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM