0

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

2 Answers 2

2

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"
  }
]
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.