How to sort array of objects by time

Can anybody help me here? I’m trying to figure out how to sort this array of objects by the time property of each object

What have you tried so far? What is your current code?

time: { type: Date, default: new Date().getTime().toString() }
This is the code from the Schema where I wanted this to return to me a value in seconds, something like “1623792654654” so I could easily sort it but for some reason in returned a date format.

I was thinking about splitting the time and sort date and time separately but I’m not sure how it’s going to work

That’s not really enough code for anyone to debug. Where is your code where you try to sort?

I think converting the time to a date object and then to seconds and sorting by the number of seconds is how I’d do it.

Edit: I wonder if just subtracting the two date objects inside of your sort would do the same thing more clearly?

1 Like

ISO8601 date time strings can be sorted with a string sort. So if you have an array of those strings you could just call .sort() on it.

That’s a little nicer than converting to dates and sorting since it’s doing less work.


Thank you to both of us, I’ll try to see how both solutions work

Huh, I’ve always been leery of string sorting numbers, but I suppose this format zero-pads the digits. Good call.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.