【发布时间】:2021-01-25 11:08:39
【问题描述】:
我有一个这样的数组:
[
{id: "1", description: "Insurance", date: "2020-12-22T00:00:00Z"},
{id: "2", description: "Salary", date: "2020-12-20T00:00:00Z"},
{id: "3", description: "Interest", date: "2020-12-20T00:00:00Z"},
{id: "4", description: "Panera", date: "2020-12-19T00:00:00Z"},
{id: "5", description: "Citibank", date: "2020-12-18T00:00:00Z"},
]
现在我想要 GroupBy 日期,然后是最新的 sortBy 日期,这是我的代码,我使用的是 lodash
const groups = _(list)
.groupBy((trans) => moment(trans.date).format('MM/DD/YYYY'))
.sortBy(group => list.indexOf(group[0]))
.value();
上面代码的数组结果如:
[
0: [
{id: "1", description: "Insurance", date: "2020-12-22T00:00:00Z"}
],
1: [
{id: "2", description: "Salary", date: "2020-12-20T00:00:00Z"},
{id: "3", description: "Interest", date: "2020-12-20T00:00:00Z"}
],
2: [
{id: "4", description: "Panera", date: "2020-12-19T00:00:00Z"}
]
3: [
{id: "5", description: "Citibank", date: "2020-12-18T00:00:00Z"}
]
]
但我希望数组返回如下:
[
{
date: 12/22/2020,
items: [
{id: "1", description: "Insurance", date: "2020-12-22T00:00:00Z"}
]
},
{
date: 12/20/2020,
items: [
{id: "2", description: "Salary", date: "2020-12-20T00:00:00Z"},
{id: "3", description: "Interest", date: "2020-12-20T00:00:00Z"}
],
},
{
date: 12/19/2020,
items: [
{id: "4", description: "Panera", date: "2020-12-19T00:00:00Z"}
]
},
{
date: 12/18/2020,
items: [
{id: "5", description: "Citibank", date: "2020-12-18T00:00:00Z"}
]
}
]
我如何用 lodash 做到这一点。
感谢您的回答。
【问题讨论】:
-
您想要的输出是无效的数组/对象表示法(最外面的大括号应该是花括号而不是方括号)。
-
但是我有日志数组和这样的结果。无论如何,我刚刚更新了我的问题。 :))
标签: javascript arrays sorting lodash