Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add up value from multiple objects

Tags:

javascript

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;
};

+=

like image 680
Peter Boomsma Avatar asked Jul 20 '26 02:07

Peter Boomsma


1 Answers

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);
};
like image 116
thitemple Avatar answered Jul 22 '26 15:07

thitemple



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!