Encountering difficulty when determining the total cost in the shopping cart

I am currently working on a basic shopping cart application and I am facing an issue when users add multiple quantities of the same product. The total is not being calculated correctly.

Here is my current logic:

Data structure for Products,

product = {
      'productName': 'Sample Product',
      'productImage': productImage,
      'rate': 100,
      'quantity': 1
    }

this.addToCartService.cartItems.subscribe(product => {
  if (product) {
    const productExistInCart = this.cartItems.find(({ productName }) => productName === product.productName);
    if (!productExistInCart) {
      this.cartItems.push(product);
      return;
    } else {
      productExistInCart.quantity++
    }
    this.totalPrice = this.cartItems
      .map(item => item.rate)
      .reduce((prev, curr) => prev + curr, 0);
  }
});

HTML Structure

 <div class="cart_box dropdown-menu dropdown-menu-right show">
    <ul class="cart_list" *ngIf="cartItems.length">
      <li *ngFor="let cartItem of cartItems; let i = index">
        <a (click)="removeFromCart(i)" class="item_remove"><i class="ion-close"></i></a>
        <a href="#"><img src="{{cartItem.productImage}}" alt="cart_thumb1">{{cartItem.productName}}</a>
        <span class="cart_quantity"> {{cartItem.quantity}} x <span class="cart_amount"> <span
              class="price_symbole">₹</span>{{cartItem.rate}}</span></span>
      </li>
    </ul>
    <div class="cart_footer">
      <p class="cart_total">Total: <span class="cart_amount"> <span
            class="price_symbole">₹</span>{{totalPrice}}</span>
      </p>
      <p class="cart_buttons"><a href="cart.html" class="btn btn-default btn-radius view-cart">View Cart</a><a
          href="checkout.html" class="btn btn-dark btn-radius checkout">Checkout</a></p>
    </div>
  </div>

I'm currently stuck and unsure how to update the total of existing items in the cart. Any help would be appreciated.

Current Output Shown Below

In the image above, the total should be 400 but it is displaying as 100. There seems to be an issue with the calculation.

Answer №1

The issue arises from failing to consider the quantity when computing the total cost. To address this, implement the following solution:

        this.totalPrice = (this.cartItems
          .map(item => item.rate * item.quantity)
          .reduce((prev, curr) => prev + curr, 0));

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Why is the current Menu Item highlight feature not functioning properly?

Why isn't the highlight current Menu Item feature working? I've checked my code, but it doesn't seem to be functioning as expected. Could you lend me a hand? Html: <section id="menu-container"> <div id="bar"><img src="b ...

What should I do to resolve the issue of ajax failing to update data randomly?

This script is designed to take the value entered into an HTML form and send it to the ../Resources/BugReport.php file. The data is then inserted into a database in that file, and the table in the ../Resources/BugDisplay.php file displays the information f ...

Recursively converting trees in JS/ES6

Currently, I am attempting to convert a tree structure provided in the following format: {"Parent": { "Child1": ["toy1"], "Child2": { "Nephew": ["toy2", "toy3"] } } } into a standardized tree form ...

Tips for accessing a new variable within an array of objects using JavaScript

How can I retrieve a new variable (section) after every 3 objects are called from an array in JavaScript ES6 Map? I've attempted to do this with an ES6 Map, but I'm not achieving the desired result. Can someone please assist me? Thank you! Below ...

An issue was encountered in the node_modules folder while attempting to access the 'Exclude' name in the lodash collection file. The error message reads: (1783,24): error TS2304: Cannot

When attempting to execute the ng serve command, I encountered an error. See below for more details. ERROR in node_modules/@types/lodash/common/collection.d.ts(1783,24): error TS2304: Cannot find name 'Exclude'. ... (error list continued) .. ...

Stubborn boolean logic that refuses to work together

Seeking guidance on resolving a persistent issue with my website that has been causing me headaches for the past few weeks. This website was created as my capstone project during a recent graduate program, where I unfortunately did not achieve all the desi ...

Click on a div in AngularJS to be directed to a specific URL

I'm currently working on developing an Angular mobile app and I want to be able to navigate to a specific URL, like www.google.com, when a particular div is clicked. Unfortunately, I'm still new to the world of Angular and struggling to achieve t ...

What are some strategies for getting neglected distribution files onto Bower despite being ignored by git?

I am in the process of creating a package for NPM and Bower. To maintain organization, I store my working files (ES6) in the src/ directory of the package and compile the distribution files (ES5, using Babel) in the lib/ directory. For version control, I ...

Transforming an array of strings to integers within a GraphQL query when they are incorporated

I need help finding a solution to pass an array of strings and embed it into a query while using React and GraphQL. The issue I'm facing is that even though the parameter is accepted as an array of strings, it gets converted to a string when embedded. ...

Notify user with a Javascript alert if there are no search results found

I have developed a search index for Chicago employees and want to create an alert if no matching records are found. However, I am struggling to determine the value that needs to be inserted in case of an empty result set. Ideally, upon submission of the fu ...

Navigating the screen reader with the cursor位

Site Design Challenge I recently discovered that the master/detail design of my website is not very accessible. The main view features a column chart where each column represents a different month. Clicking on one of these columns reveals details in a nes ...

Freezing in IE/Safari due to AJAX jQuery interactions

Feeling frustrated and seeking help. I am currently executing this particular script: <script type="text/javascript" charset="utf-8> jQuery(window).ready(function(){ //alert('running'); var sold = false; var l ...

Timing measurements in JavaScript: comparing Date.now with process.hrtime

I need to regularly calculate the time difference between specific time intervals. When it comes to performance, which method is more efficient: Date.now or process.hrtime? C:\Windows\system32>node > process.hrtime() [ 70350, 524700467 ] ...

Angular Form Container

I am in the process of creating a wrapper for forms. Everything is functioning except for the validation aspect. The issue lies in the fact that my ngForm property does not include the controls from the ng-content. My objective is to have the ngSubmit Even ...

Button Click Not Allowing Webpage Scroll

I am currently in the process of developing a website that aims to incorporate a significant amount of motion and interactivity. The concept I have devised involves a scenario where clicking on a button from the "main menu" will trigger a horizontal and ve ...

Using Node.js to retrieve a p12 certificate from the certificate repository

Is there a way to retrieve the p12 certificate from the certificate store after it has been installed? I am facing a situation where both the private key and certificate are combined in a p12 certificate and then stored in the Windows certificate store. ...

Tips for extracting the index of the chosen item from a dropdown using ReactJs and Material UI

This is the code snippet for Dropdown component implementation: <DropDownField name={formElement.name} label={formElement.name} value={formik.values[formElement.name] || ''} dropDownItems={formElement.name === &apo ...

Safari re-downloads background image when revisiting with jQuery CSS

Using jQuery to set a background-image on my website: $('.header-image').css('background-image', 'url(/img/image.jpg)'); However, upon returning to the page from Safari, the image is downloaded again, unlike Chrome and F ...

Is it considered safe to display the error message from an AJAX call for security reasons?

When I make my ajax calls, they usually follow this pattern: $.ajax({ type: 'POST', url: '/Controller/DoSomethingSpecial', contentType: 'application/json;', ...

"Implementing JavaScript Validation for Textboxes: A Step-by-Step Guide

I need some help with restricting the input of a textbox within a gridview to only 'X' or 'O'. I am not very familiar with javascript, so any guidance on how to accomplish this would be greatly appreciated. It's worth noting that t ...