首页 > 解决方案 > 如何按嵌套数组中的日期对数组进行排序

问题描述

我有一组从 REST API 返回的对象。这些对象中的每一个也包含它自己的数组,如下所示:

{
  "content": [
    {
      "id": 1,
      "name": "Name 1",
      "data": [
        {
          "id": "klqo1gnh",
          "name": "Item 1",
          "date": "2019-05-12"
        }
      ]
    },
    {
      "id": 2,
      "name": "Name 2",
      "data": [
        {
          "id": "klqo2fho",
          "name": "Item 1",
          "date": "2021-05-05"
        },
        {
          "id": "klro8wip",
          "name": "Item 2",
          "date": "2012-05-05"
        }
      ]
    }
  ]
}

然后我映射数据,并返回它,就像这样(这是一个非常精简的例子):

{content.map((item) => {
    return (
        <div>
            {item.name}
            {item.date}
            {item.id}
        </div>
    );
})}

就像你所期望的那样。然而,我需要做的是按日期排序,最好使用Moment.js,在数组中找到包含最早日期的项目,然后首先显示该项目。例如, item"id": 2包含 date 2012-05-05,因为这是数据中最早的日期,所以我需要该 item 是第一个。我真的迷路了,Moment 的文档不是很清楚。

提前致谢。

标签: javascriptarraysreactjsmomentjs

解决方案


您可以使用 Moment.js 创建一个函数,该函数接受一个数组items作为参数并返回一个按日期排序的新数组,可能是这样的:

function sortByDate(items: any[]) {
    return items.sort((first, second) => {
        if (moment(first.data.date).isSame(second.data.date)) {
            return -1; // If they have the same date, return the first item
        } else if (moment(first.data.date).isBefore(second.data.date)) {
            return -1; // If the first date is earlier, return the first item
        } else {
            return 1; // The second date is earlier, so it goes first;
        }
    })
}

然后你可以在映射之前使用这个功能content


推荐阅读