I have an array that has multiple objects. Each object has a cost. I'm trying to calculate the total price of all items combined.
static calculateCosts(shoppingCart: Array<any>):number {
let price = null;
for (let item of shoppingCart) {
price = item.price
}
console.log(price);
return price;
};
Obviously this only show the cost of the the last item in the shoppingCart. What would be a good method to add up the costs of each item?
//edit
After looking a bit more into some basic JS features this looks like a solution:
static calculateCosts(shoppingCart: Array<any>):number {
let price: number = null;
for (let item of shoppingCart) {
price += item.price
}
return price;
};
+=
You can use a reduce function to do that.
First of, because you know your array will be an array of objects containing a price member, you can type it (I understand you are using TypeScript).
Then, you can use the reduce function of an array to calculate the total.
Here's a solution:
static calculateCosts(shoppingCart: Array<{price: number}>):number {
return shoppingCart.reduce((total, item) => total + item.price, 0);
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With