Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
162 views
in Technique[技术] by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...