简体   繁体   中英

Sort String of Date & Time within array of object

Given:

[{
    date: "2020-12-23",
    session: "14:00:00-15:00:00"
}, {
    date: "2020-12-23",
    session: "10:00:00-12:00:00"
},{
    date: "2020-12-23",
    session: "12:00:00-14:00:00"
},{
    date: "2020-12-22",
    session: "14:00:00-15:00:00"
}]

How to sort by date & session? because both of them are string, especially session was range of time

Sort requires a function that compares two elements of the array and returns a number: positive, negative or a zero.

Now, since we have to handle date and time, we pick date from each component and pick the beginning of the session timestamp by splitting and fetching the first half of the session string. We concatenate the date and time to make it easy parse into milliseconds. The milliseconds can now be used in our comparator to compare the session start time.

 const v = [{ date: "2020-12-23", session: "14:00:00-15:00:00" }, { date: "2020-12-23", session: "10:00:00-12:00:00" },{ date: "2020-12-23", session: "12:00:00-14:00:00" },{ date: "2020-12-22", session: "14:00:00-15:00:00" }]; const parser = ({date, session}) => Date.parse(`${date}T${session.split('-')[0]}`) v.sort((a, b) => parser(a) - parser(b)) console.log(v)

returns

[
  {
    "date": "2020-12-22",
    "session": "14:00:00-15:00:00"
  },
  {
    "date": "2020-12-23",
    "session": "10:00:00-12:00:00"
  },
  {
    "date": "2020-12-23",
    "session": "12:00:00-14:00:00"
  },
  {
    "date": "2020-12-23",
    "session": "14:00:00-15:00:00"
  }
]

This can be accomplished using a custom comparison function. Concatenate the strings and use the built in string comparison method.

exams.sort( 
    (a,b) => (a.date+a.session).localeCompare(b.date+b.session)
)

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