【问题标题】:How can I optimize my array filtering by date times?如何按日期时间优化我的数组过滤?
【发布时间】:2025-12-03 12:45:01
【问题描述】:

我为每个数据时间编写了这个简单的过滤器数组,但不确定它是否是好方法。

示例数据:

[
  {
    "content": "test1",
    "createdAt": "2020-05-29T13:46:14.000Z"
  },
  {
    "content": "test2",
    "createdAt": "2020-05-29T13:46:14.000Z"
  },
  {
    "content": "test3",
    "createdAt": "2020-05-27T13:46:14.000Z"
  }
]

我想像这样转换它:

 {
      "Fri May 29 2020": [
        {
          "content": "test1",
          "createdAt": "2020-05-29T13:46:14.000Z"
        },
        {
          "content": "test2",
          "createdAt": "2020-05-29T13:46:14.000Z"
        }
      ],
      "Wed May 27 2020": [
        {
          "content": "test3",
          "createdAt": "2020-05-27T13:46:14.000Z"
        }
      ]
    }

还有我的代码:

let usedDates = new Set();
let logs = {};

for(let log of data) {
    const date = new Date(log.createdAt).toDateString();
    if(usedDates.has(date)) continue;

    logs[date] = data.filter((e) => date == new Date(e.createdAt).toDateString());
    usedDates.add(date);
}

是的,它有效,但不确定它是否是好方法。

【问题讨论】:

    标签: javascript arrays node.js loops filter


    【解决方案1】:

    这个简单的reduce技巧可以帮助你

    const data = [
      {
        "content": "test1",
        "createdAt": "2020-05-29T13:46:14.000Z"
      },
      {
        "content": "test2",
        "createdAt": "2020-05-29T13:46:14.000Z"
      },
      {
        "content": "test3",
        "createdAt": "2020-05-27T13:46:14.000Z"
      }
    ]
    
    const result = data.reduce((acc, value) => {
      const date = new Date(value.createdAt);
      const dateFormatted = date.toDateString();
      
      acc[dateFormatted] = [...(acc[dateFormatted] || []), value];
      
      return acc;
    
    }, {})
    
    console.log(result);

    【讨论】:

    • 非常好的解决方案。
    • 非常感谢!
    【解决方案2】:

    对于大型数组,它没有很好的性能:您遍历数据数组(for 循环),并且对于每个步骤,您都会对完整数据调用一个过滤器。 成本上升到平方。

    【讨论】: