Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

314
Views
Sort Objects By datetime in JavaScript

I have contacts that have SMS messages associated with them. Each sms record has properties such as time. Time is an timestamp string formatted as this example

2022-04-29T16:10:43-06:00

I am trying to sort this array of sms messages so that the latest one is the last one and the earliest one is the first one in the array. I thought I had it nailed down but apparently I don't. Its still not perfectly sorting at all.

this.getRecent()
    .then(contacts => {
        const sorted = contacts.map(contact => {
            contact.sms = contact.sms.sort((a,b) => (a.time.localeCompare(b.time));
            return contact;
        });
        // rest of code here
    })
    .catch(err => this.handleError(err));
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Based on your question, I'm making the assumption that the contact.sms object contains an array of objects where time is a string (localeCompare is called). Since dates can have operators applied to them, you can sort them like any number.

const dates = [
  new Date("2022-04-29T16:10:43-06:00"),
  new Date("2023-04-29T16:10:43-06:00"),
  new Date("2022-01-29T16:10:43-06:00")
]

console.log(dates)

dates.sort((a, b) => a - b)

console.log(dates)

In your case,

// Sorts dates where the least recent is first.
contact.sms = contact.sms.sort((a,b) => new Date(a.time) - new Date(b.time));
about 4 years ago · Juan Pablo Isaza Report

0

You can parse them to a Date and compare the milliseconds:

contact.sms.sort((a,b) => new Date(a.time) - new Date(b.time));

Or swap a and b if you want to reverse the order.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!