0

I have this JSON array of objects by an API call and I want to sort it by date. But the date format is in ISO and i am new to javascript so i don't know how to convert it and then sort it.

  "statuses": [
    {
      "date": "2020-01-31T05:57:32.143Z",
      "status": "Awaiting Pickup"
    },
    {
      "date": "2020-01-30T07:55:08.033Z",
      "status": "Dispatched"
    },
    {
      "date": "2020-01-18T07:55:08.033Z",
      "status": "Parcel Assigned to Rider for Delivery"
    },
    {
      "date": "2020-01-12T07:55:08.033Z",
      "status": "Delivered"
    },
    {
      "date": "2020-01-24T07:55:08.033Z",
      "status": "Returned"
    }
  ],
}
1
  • 1
    You don’t need to covert them. ISO date strings sort properly as strings. Commented Jan 31, 2020 at 6:23

1 Answer 1

3

Use sort. For conversion you can use new Date()

var obj={ "statuses": [
    {
      "date": "2020-01-31T05:57:32.143Z",
      "status": "Awaiting Pickup"
    },
    {
      "date": "2020-01-30T07:55:08.033Z",
      "status": "Dispatched"
    },
    {
      "date": "2020-01-18T07:55:08.033Z",
      "status": "Parcel Assigned to Rider for Delivery"
    },
    {
      "date": "2020-01-12T07:55:08.033Z",
      "status": "Delivered"
    },
    {
      "date": "2020-01-24T07:55:08.033Z",
      "status": "Returned"
    }
  ],
}
obj.statuses.sort((a,b)=>new Date(a.date)-new Date(b.date))
console.log(obj)

Sign up to request clarification or add additional context in comments.

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.