I have two JavaScript arrays containing objects:
const types = [
{
id: 1,
name: 'Paint',
unit: 'L',
},
{
id: 2,
name: 'Resin',
unit: 'mL',
},
{
id: 3,
name: 'Fiberglass',
unit: 'yd',
}
];
const items = [
{
id: 1,
type_id: 1,
name: 'Brand x paint',
qty: 5,
},
{
id: 2,
type_id: 1,
name: 'Brand y paint',
supplier: 'brand y',
qty: 3,
},
{
id: 3,
type_id: 2,
name: 'Brand x resin',
qty: 5,
},
{
id: 3,
type_id: 2,
name: 'Brand y resin',
qty: 2,
},
{
id: 3,
type_id: 2,
name: 'Brand z resin',
qty: 3,
},
{
id: 3,
type_id: 2,
name: 'Brand x fiberglass',
qty: 7,
},
{
id: 3,
type_id: 2,
name: 'Brand y fiberglass',
qty: 9,
},
];
I am attempting to add a new property called total_qty to each object in the types array. This property should represent the sum of quantities for each respective type from the items array. I tried using the map function and filtering the items array based on type_id, but it is not working as expected:
const itemTypes = types.map( (type) => {
type.total_qty = items
.filter((item) => item.type_id === type.id)
.reduce((sum, item) => sum += item.qty, 0)
}
)
If there is a more efficient way to achieve this or if you have any suggestions to improve my current approach, I would greatly appreciate it. Thank you!