My data structure includes an array as shown below:
BasketDish
[
{
id: string;
quantity: number;
Dish: AsyncItem<Dish | undefined>;
basketID: string;
createdAt?: string | null;
updatedAt?: string | null;
basketDishDishId?: string | null;
}
]
Dish
[
{
id: string;
name: string;
price: number;
},
{
id: string;
name: string;
price: number;
}
]
I am looking to group the array by Dish.id and then create a new array that calculates the total quantity and price for each dish
Starting from:
[
{
id: 1,
name: BBQ Burger,
price: 17
},
{
id: 2,
name: CheeseBurger,
price: 15
},
{
id: 2,
name: CheeseBurger,
price: 15
},
]
The desired result is:
[
{
id: 1,
name: BBQ Burger,
price: 17,
total: 17,
quantity: 1
},
{
id: 2,
name: CheeseBurger,
price: 15,
total: 30,
quantity: 2
},
]
I have attempted various methods like using groupBy and merge, but I haven't been successful
UPDATE
Thanks @BioStunt
I just needed to modify your solution to group by Dish.id instead of id
/**
* Merge Dishes with same id
*/
const groupedItems = chain(basketDishes)
/** group items by key "id" */
.groupBy(a => a.Dish?.id)
/** convert grouped items */
.map((items, id) => ({
id: id,
dishId: items[0]?.Dish?.id,
name: items[0].Dish?.name,
quantity: items.length,
total: items.reduce((acc, item) => acc + item.Dish?.price!, 0),
}))
/** get result of chain */
.value();