Search code examples
javascriptarraysjsonloopscart

I want to loop through my array and calculate my values-JavaScript


I want to able to loop my arrays and calculate the total price and display it in the console. this is suppose to be a cart application. I assign all the anchor tags to cart variable that loops through the anchors tag and assign the the tags to the values in my beverages array to be able to display it but i cant display the total amount of all the prices.

html

<section id="menu">
    <h2>Menu</h2>
    <p>Click an item to add it to your order.</p>
    <ul class="coffeeMenu">
        <li><a id="espresso" class="add-to-cart" href="#"></a></li>
        <li><a id="latte" class="add-to-cart" href="#"></a></li>
        <li><a id="cappuccino" class="add-to-cart" href="#"></a></li>
        <li><a id="coffee" class="add-to-cart" href="#"></a></li>
        <li><a id="biscotti" class="add-to-cart" href="#"></a></li>
        <li><a id="scone" class="add-to-cart " href="#"></a></li>
    </ul>
</section>

javascript

  let cart = document.querySelectorAll('.add-to-cart');

  let beverages = [{
    name: 'espresso',
    price: 1.95,
    inCart: 0,
},
{
    name: 'latte',
    price: 2.95,
    inCart: 0,
},
{
    name: 'cappuccino',
    price: 3.45,
    inCart: 0,
},
{
    name: 'coffee',
    price: 1.75,
    inCart: 0,
},
{
    name: 'biscotti',
    price: 1.95,
    inCart: 0,
},
{
    name: 'scone',
    price: 2.95,
    inCart: 0,
},
   //run a loop to through the images and the array
 for (let i = 0; i < cart.length; i++) {
cart[i].addEventListener('click', () => {
    cartNumber(beverages[i]);
    // totalCost(beverages[i]);
    })
  }



   // display the prices in the textarea

 let cartNumber = (beverages) => {
document.getElementById("order").textContent += beverages.name + " = "+ beverages.price 
    +"\n"
let productNumbers = localStorage.getItem('cartNumber')
productNumbers = parseInt(productNumbers);
if (productNumbers) {
    localStorage.setItem('cartNumber', productNumbers + 1);
    document.getElementById("total").textContent
} else {
    localStorage.setItem("cartNumber", 1);
    document.getElementById('tot').textContent = 1;

   for (let i = 0; i < cart.length; i++) {
    cart[i].addEventListener('click', () => {
    for(var price in beverages ) {
        console.log(price, beverages["prices"])
    }
})
   }

      console.log(beverages["price"]);

    let totalCost = (beverages) => {
        let cartCost = localStorage.getItem('totalCost');
        console.log(cartCost)
        if(cartCost != null) {
            cartCost = parseInt(cartCost);
            localStorage.setItem("totalCost", cartCost + beverages.price)
            document.getElementById("total").textContent = "$" + cartCost ;
            document.getElementById("cartTotal").textContent = cartCost;
    
    
            
        } else {
        localStorage.setItem("totalCost",  beverages.price)
        }
    }
   

Solution

  • Instead of writing too much and looping .... See this , it might help you build what you are willing too

    HTML

    <section id="menu">
      <h2>Menu</h2>
      <p>
        Click an item to add it to your order.
      </p>
      <ul class="coffeeMenu">
        <li><a onclick="add_to_cart('espresso')" class="add-to-cart">espresso</a></li>
        <li><a onclick="add_to_cart('latte')" id="latte" class="add-to-cart">latte</a></li>
        <li><a onclick="add_to_cart('cappuccino')" id="cappuccino" class="add-to-cart">cappuccino</a></li>
        <li><a onclick="add_to_cart('coffee')" id="coffee" class="add-to-cart">coffee</a></li>
        <li><a onclick="add_to_cart('biscotti')" id="biscotti" class="add-to-cart">biscotti</a></li>
        <li><a onclick="add_to_cart('scone')" class="add-to-cart ">scone</a></li>
      </ul>
      <button id="total" onclick="cart_total()">Total</button>
    </section>
    

    JS

      let beverages = [{
        name: 'espresso',
        price: 1.95
      },
        {
          name: 'latte',
          price: 2.95
        },
        {
          name: 'cappuccino',
          price: 3.45
        },
        {
          name: 'coffee',
          price: 1.75
        },
        {
          name: 'biscotti',
          price: 1.95
        },
        {
          name: 'scone',
          price: 2.95
        }]
    
      let cart = [];
      let sum = 0;
    
    
      function add_to_cart(item) {
        let qty = prompt('Please enter quantity ')
        qty = parseInt(qty);
        if (isNaN(qty)) {
          qty = 1
        }
        cart.push({
          name: item,
          quantity: qty
        });
      }
    
      function cart_total() {
        console.log(cart)
        cart.forEach(item => {
          beverages.forEach(beverage => {
            if (beverage.name === item.name) {
              sum += beverage.price * item.quantity
            }
          })
        });
        console.log(sum)
      }