如何按嵌套数组中的日期对数组进行排序

时间:2021-05-06 18:59:24

标签: javascript arrays reactjs momentjs

我有一个从 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,在数组中查找包含最早日期的项目,然后首先显示该项目。例如,项目 "id": 2 包含日期 2012-05-05,并且由于这是数据中最早的日期,我需要该项目是第一个。我真的迷路了,Moment 的文档不是很清楚。

提前致谢。

2 个答案:

答案 0 :(得分:1)

您可以使用 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之前使用这个函数

答案 1 :(得分:-1)

你使用过 JavaScript 数组的 sort 方法吗?

array.sort((a, b) => a.value - b.value)

如果 a.value - b.value 大于 0,则 b 是前一项而不是 a。

相关问题