1

I know that my question was asked a few times here, but I didn't find a working solution :(

My array in the data property is currently looking like this:

products: [{
    name: 'Product A',
    price: '10'
}, 
{
    name: 'Product B',
    price: '30'
}, 
{
    name: 'Product C',
    price: '20'
}]

Function to sum up the prices:

sumTotal() {
    let basket_total = [];
    this.products.forEach(val => {
        basket_total += val.price;
    });
    console.log(basket_total);
}

My result is 103020 instead of 60. I also tried other ways, but every time I got the same result. What can I do?

Thanks!

1
  • basket_total should be a number, not an array: let basket_total = 0 Commented Nov 25, 2019 at 15:47

1 Answer 1

2

Yes , because you add this values as array items , you should do it :

sumTotal() {
    let basket_total = 0;
    this.products.forEach(val => {
        basket_total += Number(val.price);
       //or if you pass float numbers , use parseFloat()
    });
    console.log(basket_total);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.