I've got an object array which I have to group and sort:
[
{
id: 123,
group: 'abc',
metadata: {
name: 'tom'
},
date: ISODate("2019-07-08T20:33:40.475Z")
},
{
id: 456,
group: 'def',
metadata: {
name: 'bob'
},
date: ISODate("2019-07-08T20:33:40.475Z")
},
{
id: 789,
group: 'def',
metadata: {
name: 'bob'
},
date: ISODate("2019-07-10T20:33:40.475Z")
},
{
id: 234,
group: 'ghi',
metadata: {
name: 'frank'
},
date: ISODate("2019-07-10T20:33:40.475Z")
},
{
id: 567,
group: 'abc',
metadata: {
name: 'tom'
},
date: ISODate("2019-07-10T20:33:40.475Z")
}
]
Firstly I need to group the elements by the group value, then I need to sort the elements of this grouped array by date.
For grouping I've tried this:
const result = array.reduce(function (r, a) {
r[a.group] = r[a.group] || [];
r[a.group].push(a);
return r;
}, Object.create(null));
But the result is not as expected and the elements are not sorted by date.
The result could/should look something like this:
[
[
{
id: 123,
group: 'abc',
metadata: {
name: 'tom'
},
date: ISODate("2019-07-08T20:33:40.475Z")
},
{
id: 567,
group: 'abc',
metadata: {
name: 'tom'
},
date: ISODate("2019-07-10T20:33:40.475Z")
}
],
[
{
id: 456,
group: 'def',
metadata: {
name: 'bob'
},
date: ISODate("2019-07-08T20:33:40.475Z")
},
{
id: 789,
group: 'def',
metadata: {
name: 'bob'
},
date: ISODate("2019-07-10T20:33:40.475Z")
}
],
[
{
id: 234,
group: 'ghi',
metadata: {
name: 'frank'
},
date: ISODate("2019-07-10T20:33:40.475Z")
}
]
]
ISODatefunction, and where are you trying to.sortthe subarrays as desired? I don't see either of those in the code