Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Javascript – Sort array of objects by property date

I have the following response from a service:

const arrDate = [
  {
    "id":1,
    "birthDate":"2022-06-30T14:38:28.003"
  },
  {
    "id":2,
    "birthDate":"2022-06-30T14:36:48.50"
  },
  {
    "id":3,
    "birthDate":"2022-06-30T14:35:40.57"
  },
  {
    "id":4,
    "birthDate":"2022-06-30T13:09:58.451"
  },
  {
    "id":5,
    "birthDate":"2022-06-30T14:11:27.647"
  },
  {
    "id":6,
    "birthDate":"2022-06-30T14:55:41.41"
  },
  {
    "id":7,
    "birthDate":"2022-02-22T11:55:33.456"
  }
]

To sort it by date I do the following:

const sortDate = arrDate.sort(function(a, b) {
  return new Date(a.birthDate) > new Date(b.birthDate);
});

But the value of "sortDate" is not correct:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[
   {
      "birthDate":"2022-06-30T14:38:28.003",
      "id":1
   },
   {
      "birthDate":"2022-06-30T14:36:48.50",
      "id":2
   },
   {
      "birthDate":"2022-06-30T14:35:40.57",
      "id":3
   },
   {
      "birthDate":"2022-06-30T13:09:58.451",
      "id":4
   },
   {
      "birthDate":"2022-06-30T14:11:27.647",
      "id":5
   },
   {
      "birthDate":"2022-06-30T14:55:41.41",
      "id":6
   },
   {
      "id":7,
      "birthDate":"2022-02-22T11:55:33.456"
   }
]

Should be:

[
   {
      "birthDate":"2022-06-30T14:55:41.41",
      "id":6
   },
   {
      "birthDate":"2022-06-30T14:38:28.003",
      "id":1
   },
   {
      "birthDate":"2022-06-30T14:36:48.50",
      "id":2
   },
   {
      "birthDate":"2022-06-30T14:35:40.57",
      "id":3
   },
   {
      "birthDate":"2022-06-30T14:11:27.647",
      "id":5
   },
   {
      "birthDate":"2022-06-30T13:09:58.451",
      "id":4
   },
   {
      "id":7,
      "birthDate":"2022-02-22T11:55:33.456"
   }
]

How can i solve it?, thanks

>Solution :

The problem is that the comparison function is supposed to return a positive number for if a should be after b, negative if b should be after a, and zero if they should keep the same order. Your function is returning true and false, JS converts true to 1 and false to zero. That means you are never telling sort to put b after a.

have the function return

return new Date(a.birthDate) > new Date(b.birthDate) ? -1 : 1;
// copied from a comment
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading