[英]How can I optimize my array filtering by date times?
我为每个数据时间编写了这个简单的过滤器数组,但不确定它是否是好方法。
示例数据:
[
{
"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);
}
是的,它有效,但不确定它是否是好方法。
这个简单的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);
对于大的 arrays 来说,它的性能并不好:您遍历数据数组(for循环),并且对于每个步骤,您都对完整数据调用一个过滤器。 成本上升到平方。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.