I have an array like so:
[
{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"},
]
Now I want GroupBy date, then sortBy date newest, here is my code, I'm using lodash
const groups = _(list)
.groupBy((trans) => moment(trans.date).format('MM/DD/YYYY'))
.sortBy(group => list.indexOf(group[0]))
.value();
The array result of code above like:
[
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"}
]
]
But I would like the array to return like below:
[
{
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"}
]
}
]
How I can do this with lodash.
Thank for your answer.
question from:
https://stackoverflow.com/questions/65883562/groupby-array-and-then-sortby-date-that-array-using-lodash