How to add multiple datalayer parameters with for loop?

284 Views Asked by At

I have a datalayer with parameter "Price" which I want to add, e.g. 799 + 95 + 95.

enter image description here

DigitalData[0].Cart.Items[0].Price 

Returns "799.00"

Believe one could JavaScript For Loop to achieve the subtraction of price that I'm looking for. But I'm not familiar how to type this scenario. Am I going towards the right direction? See below code?

for (i = 0; i < items.length; i++) { 
    DigitalData[0].Cart.Items[i].Price;
}
4

There are 4 best solutions below

1
AudioBubble On BEST ANSWER

You need a variable to store the sum:

var sum = 0;
var items = DigitalData[0].Cart.Items;
for (i = 0; i < items.length; i++) { 
    sum += parseInt(items[i].Price);
}
0
Himanshu Tanwar On
var totalPrice = 0;    
for (i = 0; i < items.length; i++) { 
        var price = DigitalData[0].Cart.Items[i].Price;
        price = parseFloat(price);
        totalPrice += price;
    }
0
Nina Scholz On

You could use Array#reduce:

var sum = DigitalData[0].Cart.Items.reduce(function (r, a) {
        return r + +a.Price;
    }, 0);
0
Timvr01 On

You where on the right way, this is the complete solution:

var sum=0;
for (i = 0; i < items.length; i++) { 
    sum+=DigitalData[0].Cart.Items[i].Price;
}