My task involves dealing with an array of objects called Product
.
The structure of the Product
class is as follows:
class Product {
id: string;
type: string;
price: number;
constructor(id: string, type: string, price: number) {
this.id = id;
this.type = type;
this.price = price;
}
}
To group the array of products based on their type
property, I attempted to utilize the array reduce function:
const groupedProducts = productList.reduce((group, prod) => {
const prodType = prod.type;
group[prodType] = group[prodType] ?? [];
group[prodType].push(prod);
return group;
}, {});
However, the code above resulted in a compiler error:
No index signature with a parameter of type 'string' was found on type '{}'.
It seems that the issue stems from the undefined object index within the initial value {}
, which led me to modify it to {string: Product[]}
. Unfortunately, this adjustment did not resolve the error.
You can view the complete code here.
I am seeking assistance on eliminating this error and successfully obtaining the desired grouped products.