Creating a new array grouped by the property 'desc'
of the objects within an existing array is my current task. Here is how I envision it:
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 believe using the reduce()
higher-order function would be the most efficient way to accomplish this. However, I am facing some challenges in adapting the solutions I've found to fit my array structure. Any guidance on how to approach this would be greatly appreciated!