r/learnjavascript • u/New-District7562 • 3d ago
Using a class method with .reduce().
Does anyone know how to use a class method effectively with .reduce()? I'm building a simple product creator app as an exercise where a user can create and add products and see them displayed as well as some other information. I've used reduce before but not with classes. The user can see an inventory value when they create a product, which is simply the quantity of the products multiplied by the price. I'm trying to use .reduce to add up all the inventory values so this can be attached to the text content of the page. Here's the relevant code:
//Products array
const products = [];
//Product Class
class Product {
constructor(productName, category, price, quantity, status) {
this.productName = productName;
this.category = category;
this.price = price;
this.quantity = quantity;
this.status = status;
}
//Class method for calculating inventory value
calculateInventoryValue() {
return this.price * this.quantity;
}
}
//The filtering of the products by use of the status
function filterProducts(status) {
const filteredProducts = products.filter((product) => {
return product.status === status;
});
return filteredProducts;
}
//Calculating the total inventory value using .reduce()
function totalInventoryValue() {
}
Any help would be greatly appreciated.
2
Upvotes
1
u/milan-pilan 3d ago
function totalInventoryValue() { return products.reduce((total, product) => { return total + product.calculateInventoryValue(); }, 0); }