【问题标题】:JavaScript Array: Order Nested Object by Key [duplicate]JavaScript数组:按键排序嵌套对象[重复]
【发布时间】:2022-02-06 21:30:39
【问题描述】:

我有以下嵌套对象。我想遍历每个项目(latest.sentTime),然后按“sentTime”对对象本身进行排序。这样最新的消息就在最上面。我怎样才能做到这一点?

在下面的例子中,“0”和“1”基本上需要交换,因为“1”有一个更新的“sentTime”。

【问题讨论】:

  • yourArray.sort(({ latest: { sentTime: a } }, { latest: { sentTime: b } }) => b.localeCompare(a));.

标签: javascript node.js arrays json sorting


【解决方案1】:

const arr = [ 
  { latest: { sentTime: '2022-02-05T19:15:32.000Z' } },
  { latest: { sentTime: '2022-02-06T22:12:00.000Z' } } 
];

const sentTimes = arr
  .map(({ latest }) => latest.sentTime)
  .sort((a, b) => new Date(b) - new Date(a));

console.log(sentTimes);

【讨论】:

    猜你喜欢
    • 2019-10-27
    • 2022-08-17
    • 1970-01-01
    • 2017-10-04
    • 1970-01-01
    • 2023-01-19
    • 1970-01-01
    • 1970-01-01
    • 2017-05-31
    相关资源
    最近更新 更多