0

I have an array that get the quantity of each product and I want to sum the numbers of them but when I use reduce it only put the numbers in array next to each other in red shopping button based on the picture!

This is my code:

function updateTotal() {
  let total = 0;
  let arr = [];
  const items = document.querySelectorAll(".prodItem");
  for (i = 0; i < items.length; i++) {
    priceAmount = items[i].querySelectorAll(".prodPrice")[0];
    productQuantity = items[i].querySelectorAll(".num")[0];
    const quantity = productQuantity.value;
    const priceContent = priceAmount.innerText;
    const price = priceContent.replace("$", "");
    total += price * quantity;
    document.querySelector(".total-amount").innerText = "$" + total;
    arr.push(quantity);
  }

  counter.innerText = arr.reduce(
    (accumulator, currentValue) => accumulator + currentValue
  );
}

enter image description here

Ivar
  • 6,138
  • 12
  • 49
  • 61
  • 2
    Does this answer your question? [Adding two numbers concatenates them instead of calculating the sum](https://stackoverflow.com/questions/14496531/adding-two-numbers-concatenates-them-instead-of-calculating-the-sum) – Ivar Oct 19 '20 at 09:57
  • 3
    Your array of numbers is an array of strings. You need to convert those strings to numbers before you add the values. (Either inside your `reduce` or when you add them to to the array.) (Personally I'd just change `productQuantity.value` to `Number(productQuantity.value)`.) – Ivar Oct 19 '20 at 09:59

0 Answers0