[英]GroupBy array and then sortBy date that array using lodash
我有一個像這樣的數組:
[
{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 做到這一點。
謝謝你的回答。
如果 vanilla JS 解決方案適合您,您可以使用Array.prototype.reduce()
對對象進行分組,並使用Array.prototype.sort()
對 output 進行排序:
const src = [ {id: "5", description: "Citibank", date: "2020-12-18T00:00:00Z"}, {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"}, ], result = [...src.reduce((acc,o) => { const [yyyy, mm, dd] = o.date.split(/[\-T]/), key = [mm, dd, yyyy].join('/'), group = acc.get(key) group? group.items.push(o): acc.set(key, {date: key, items: [o]}) return acc }, new Map).values()].sort(({date:a},{date:b}) => b.localeCompare(a)) console.log(result)
.as-console-wrapper{min-height:100%;}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.