I have the following code
function getNumberWithCommas(number) { return number.toString().replace(/\B(?=(\d{3})+(?!\d))/g, "."); } var price = [ 6599, 7659, 899, 569, 899, 279, 219, 1797, 3999, 2769, 599, 1349, 2149, 219, 219, 519, 2499, 2949, 5149, 7689, 15999, ]; for (let i = 0; i < 20; i++) { var productPrice = document.createElement("span"); productPrice.className = "price"; productPrice.setAttribute("id", `price-id-${i}`); var calculatedPrice = price[i] * quantities[i]; productPrice.textContent = `R$ ${getNumberWithCommas(calculatedPrice)},00`; precoTotalDiv.appendChild(productPrice); var totalPrice = []; totalPrice.push(calculatedPrice); console.log(totalPrice); } It dynamically creates prices for products based on their quantity in the cart and their price. I would like to save these values (calculatedPrice) inside an array so I can get a total price (sum of all the prices) at the bottom of the cart.
It is adding calculatedPrice to totalPrice[], but it only adds one value, the length of the array remains one. Once I click another product, calculatedPrice gets overwritten with another products price. I would like to get a sum of all the prices generated, not the sum of only one product.
array.push(calculatedPrice)in the loop.total += calculatedPricein the loop.