简体   繁体   English

Javascript - 按属性日期对对象数组进行排序

[英]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:但是“sortDate”的值不正确:

[
   {
      "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我该如何解决?,谢谢

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.问题是比较 function 应该返回一个正数,如果 a 应该在 b 之后,如果 b 应该在 a 之后,则返回负数,如果它们应该保持相同的顺序,则返回零。 Your function is returning true and false, JS converts true to 1 and false to zero.您的 function 正在返回 true 和 false,JS 将 true 转换为 1,将 false 转换为零。 That means you are never telling sort to put b after a.这意味着您永远不会告诉 sort 将 b 放在 a 之后。

have the function return有 function 返回

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

ascending上升

return new Date(a.birthDate) - new Date(b.birthDate);

descending下降

return new Date(b.birthDate) - new Date(a.birthDate);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM