Based on an array I wanna create a new array which is grouped by an property 'desc' of the contained objects. Like this:
const sourceArray = [
{ id: 'id1', sourceDesc: 'foo', prop1: 'ignoreme', prop2: 'ignoreme' }
{ id: 'id2', sourceDesc: 'foo', prop1: 'ignoreme', prop2: 'ignoreme' }
{ id: 'id3', sourceDesc: 'bar', prop1: 'ignoreme', prop2: 'ignoreme' }
{ id: 'id4', sourceDesc: 'baz', prop1: 'ignoreme', prop2: 'ignoreme' }
];
const targetArray = [
{ desc: 'foo', ids: [
{ id: 'id1', prop1: 'ignoreme', prop2: 'ignoreme' },
{ id: 'id2', prop1: 'ignoreme', prop2: 'ignoreme' }
]},
{ desc: 'bar', ids: [
{ id: 'id3', prop1: 'ignoreme', prop2: 'ignoreme' }
]},
{ desc: 'baz', ids: [
{ id: 'id4', prop1: 'ignoreme', prop2: 'ignoreme' }
]}
];
I guess the reduce() high-order-function will be the best / modern / efficient way to achieve this ... And if so, how? I'm a bit stuck in my head... I found some answers on this topic, but I'm not able to adapt them to my array structure :-(