I have an array of objects (groceryArray) that I would like to organize into an object by the groupId property (object keys) and finally sort these keys by the groupDisplayOrder property. See finalOutput for desired result.
const groceryArray = [
{ id: 'apples', groupId: 'produce', groupDisplayOrder: 1 },
{ id: 'chicken', groupId: 'meat', groupDisplayOrder: 3 },
{ id: 'shrimp', groupId: 'seafood', groupDisplayOrder: 4 },
{ id: 'milk', groupId: 'dairy', groupDisplayOrder: 2 },
{ id: 'carrots', groupId: 'produce', groupDisplayOrder: 1 },
{ id: 'salmon', groupId: 'seafood', groupDisplayOrder: 4 }
]
Desired Result
const finalOutput = {
produce: [{ id: 'apples', groupId: 'produce', groupDisplayOrder: 1 }, { id: 'carrots', groupId: 'produce', groupDisplayOrder: 1 }],
dairy: [{ id: 'milk', groupId: 'dairy', groupDisplayOrder: 2 }],
meat: [{ id: 'chicken', groupId: 'meat', groupDisplayOrder: 3 }],
seafood: [{ id: 'shrimp', groupId: 'seafood', groupDisplayOrder: 4 }, { id: 'salmon', groupId: 'seafood', groupDisplayOrder: 4 }]
}
Here's my current code ... I think I may be doing too many steps. I'm wondering if there is a way to reduce and sort at the same time?
const groceriesGroupedById = groceryArray.reduce((acc, cur) => {
if (cur.groupId) {
(acc[cur.groupId] || (acc[cur.groupId] = [])).push(cur)
}
return acc
}, {})
const sortedGroupIds = Object.keys(groceriesGroupedById).sort((a, b) => {
return groceriesGroupedById[a][0].groupDisplayOrder - groceriesGroupedById[b][0].groupDisplayOrder
})
const finalOutput = sortedGroupIds.reduce((acc, key) => ( acc[key] = groceriesGroupedById[key], acc ), {})