Skip to content
Advertisement

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:

[
   {
      "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

Advertisement

Answer

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
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement