I know that, there are countless of questions about group by one property from an array of object. But what I want to do is a litte more specific:
const lists = [
{ groupKey: 'ABC', key: 'r8', timestamp: '2014', index: 2 },
{ groupKey: 'ABC', key: 'q8', timestamp: '2012', index: 0 },
{ groupKey: 'ABC', key: 'w8', timestamp: '2013', index: 1 },
{ groupKey: 'CDE', key: 'r7', timestamp: '2019', index: 0 }
]
Result should be grouped by groupKey and sorted by index
(indexes here are iterators 0,1,2,3... so no need to actually be sorted but rather to be placed in a right order of an array. Example: array[index] = ... ).
This should look like:
{
ABC: [
{ key: 'q8', timestamp: '2012', index: 0 },
{ key: 'w8', timestamp: '2013', index: 1 },
{ key: 'r8', timestamp: '2014', index: 2 }
],
CDE: [
{ key: 'r7', timestamp: '2019', index: 0 }
]
}
I have tried to group by without sorting:
const result = lists.reduce((r, item) => {
let { groupKey, ...rest } = item
r[item.groupKey] = [...(r[item.groupKey] || []), rest]
return r
}, {})
And with sorting, not successful but you know what I mean:
const result = lists.reduce((r, item) => {
let { groupKey, ...rest } = item
r[item.groupKey][item.index] = rest //err: can not set property 2 of undefined
return r
}, {})
Any suggestions are appreciated