What method can be used to determine the discount for individual items within an array when using reduce()?

I am trying to figure out how to calculate a 15% discount for each item in an array along with the total amount. I have already managed to calculate and display the total discount for all items using the reduce() method, but I'm stuck on how to calculate the discount for each item separately with reduce(). Is there a workaround for this or should I consider a different approach?

function getDomNodesBySelector(selector) {
  return Array.from(document.querySelectorAll(selector));
}

document.querySelector('.total__button').addEventListener('click', applyDiscount);

function applyDiscount() {
  let items = getDomNodesBySelector(".price-value");
  let numDiscount = 15;
  let totalValue = items.reduce((acc, cur) => acc + (1 - (numDiscount / 100)) * cur.innerText, 0);
  document.querySelector(".total-price-value").innerText = totalValue;
}
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Shopping Cart</title>
    <link rel="stylesheet" href="https://code.s3.yandex.net/web-code/entrance-test/lesson-2/task-2/fonts.css">
    <link rel="stylesheet" href="style.css">
  </head>
  <body class="page">
  <h1 class="page__title">Cart</h1>
  <section class="chosen-items">
    <article class="card">
      <img src="https://code.s3.yandex.net/web-code/entrance-test/jacket.png" alt="" class="card__image">
      <div class="card__description">
        <h2 class="card__title">Have A Good Time x FA Two Tone Jacket</h2>
        <p class="card__text">Color: Green/Orange</p>
        <p class="card__text">Size: M</p>
        <p class="card__text">Quantity: 1</p>
      </div>
      <div class="card__price">
        <p class="card__rub price-default"><span class="price-value">15890</span> rub.</p>
      </div>
    </article>
    <article class="card">
      <img src="https://code.s3.yandex.net/web-code/entrance-test/vans.png" alt="" class="card__image">
      <div class="card__description">
        <h2 class="card__title">Vans Old Skool Sneakers</h2>
        <p class="card__text">Color: Black/White</p>
        <p class="card__text">Size: 43</p>
        <p class="card__text">Quantity: 1</p>
      </div>
      <div class="card__price">
        <p class="card__rub price-default"><span class="price-value">6390</span> rub.</p>
      </div>
    </article>
    <article class="card">
      <img src="https://code.s3.yandex.net/web-code/entrance-test/pop-DRS.png" alt="" class="card__image">
      <div class="card__description">
        <h2 class="card__title">Pop DRS Denim Stonewashed Jeans</h2>
        <p class="card__text">Color: Blue</p>
        <p class="card__text">Size: S</p>
        <p class="card__text">Quantity: 1</p>
      </div>
      <div class="card__price">
        <p class="card__rub price-default"><span class="price-value">11290</span> rub.</p>
      </div>
    </article>
    <article class="card">
      <img src="https://code.s3.yandex.net/web-code/entrance-test/by-parra.png" alt="" class="card__image">
      <div class="card__description">
        <h2 class="card__title">By Parra Belt</h2>
        <p class="card__text">Color: Multi</p>
        <p class="card__text">Size: S</p>
        <p class="card__text">Quantity: 1</p>
      </div>
      <div class="card__price">
        <p class="card__rub price-default"><span class="price-value">8550</span> rub.</p>
      </div>
    </article>
    <article class="card">
      <img src="https://code.s3.yandex.net/web-code/entrance-test/board.png" alt="" class="card__image">
      <div class="card__description">
        <h2 class="card__title">Fucking Awesome Drawings 2 Pink Skateboard</h2>
        <p class="card__text">Color: Fluorescent Pink</p>
        <p class="card__text">Size: One Size</p>
        <p class="card__text">Quantity: 1</p>
      </div>
      <div class="card__price">
        <p class="card__rub price-default"><span class="price-value">4790</span> rub.</p>
      </div>
    </article>
  </section>
  <section class="total page__total">
    <button class="total__button">Apply 15% Discount Coupon</button>
    <div class="total__prices">
      <h2 class="total__title">Total:</h2>
      <p class="total__rub price-default"><span class="total-price-value">46910</span> rub.</p>
    </div>
  </section>
  <script src="./task.js"></script>
  </body>
</html>

Answer №1

As you iterate through the array of price items and use the reduce function, you are already processing each item to calculate the discounted price. Before updating the accumulator in the reduce function, make sure to update the value of the item.

Make changes to each item and add to the total:

// CHANGE:
// let totalValue = items.reduce((acc, cur) => acc + (1 - (numDiscount / 100)) * cur.innerText, 0);

// TO:
let totalValue = items.reduce((acc, cur) => {
    let itemdisc = (1 - (numDiscount / 100)) * cur.innerText; // calculate item discount
    cur.innerText = itemdisc; // update item
    return acc + itemdisc; // update total
}, 0);

Prevent applying the discount multiple times:

document.querySelector('.total__button').disabled = true;

Updated script:

function getDomNodesBySelector(selector) {
  return Array.from(document.querySelectorAll(selector));
}

document.querySelector('.total__button').addEventListener('click', applyDiscount);

function applyDiscount() {
  let items = getDomNodesBySelector(".price-value");
  let numDiscount = 15;
  let totalValue = items.reduce((acc, cur) => {
      let itemdisc = (1 - (numDiscount / 100)) * cur.innerText; // calculate item discount
      cur.innerText = itemdisc; // update item
      return acc + itemdisc; // update total
  }, 0);
  document.querySelector(".total-price-value").innerText = totalValue;

  // prevent discount from being applied more than once
  document.querySelector('.total__button').disabled = true;
}

Answer №2

Here's a simple JavaScript function:

function extractPrices(){

   var prices = document.querySelectorAll('.price-value');
   return Array.from(prices).map(price => price.textContent);

}

console.log(extractPrices())

This function will get the individual prices from the HTML and store them in an array for easy use.

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

Hey there everyone, I was wondering how to send both single and multiple values to a database using JavaScript and JSON endpoints with a Spring Web API

{ "id": 178, "stockin_date": "2022-11-15T08:18:54.252+00:00", "effective_date": null, "expired_date": null, "create_date": null, "update_date&q ...

browsing and extracting information from JSON datasets

Currently, I am utilizing ajax to fetch a json string from the server and then employing eval to convert it into an object. However, when I loop through the data obtained from the json, only the key is displayed. Is there a way to extract the value associa ...

There appears to be an issue where the session object cannot be retrieved by the Struts2 action

I have a struts2 action that is invoked by a JavaScript function. The JavaScript function uses uploadify to enable multiple file uploads: <script type="text/javascript"> $(document).ready(function() { $("#fileupload").uploadify({ ...

Implementing URL routing and error handling in a Node.js application using the Express framework

As a newcomer to node.js, I appreciate your patience. I've been experimenting with node.js and the express module. I had an idea for handling browser requests and now I have a simple question: Is this approach good practice, or is there a better sol ...

What is the method to retrieve the character set of response data in an Ajax request?

Ajax Request: $("button").click(function(){ $.ajax({url: "demo.html", success: function(result){ $("#div1").html(result); }}); }); In this code snippet, an Ajax request is made to fetch data from the demo.html file. The response data is s ...

Reveal the table only once a search has been completed

Currently, I am in the process of developing a small project and my aim is to have the table with the results appear only upon clicking the button or initiating a search. If you are interested, you can view it at this link: . My objective is to keep the t ...

Utilizing Angular's locale feature for currency formats

Exploring Angular (1.6.4) is a new adventure for me, and I have a task at hand to customize currency symbols across my webpage by configuring $locale in this Angular application. Currently, the code snippet looks like this: {{myCtrl.getPrice() | currency ...

How can I invoke a function within a directive-generated HTML element's scope?

I created a custom directive that utilizes element.html() to set the HTML content. Within this HTML code, I would like to be able to invoke functions from the scope where the directive is being used. Here's an example: app.directive('myDirective ...

Dealing with adding up optional values from v-model in Vue.js can be a challenging task

Within this function, I need to display the remaining amount. remainingAmount: function() { return parseFloat(this.sumAmount) - (parseFloat(this.cash) + parseFloat(this.kNet) + parseFloat(this.kNetOnline)); } The three parameters cash ...

Enable the ability to scroll and click to navigate an overlapping Div element

A customer has a website with a dark teal design and is not pleased with the appearance of the scroll bar, as it disrupts the overall style. The client requested that I find a solution without using third-party libraries, and one that they can easily under ...

Automatically populate dynamic fields with ajax response

Using auto-fill with an ajax request works well for static fields. For example: $this->registerJs("$(document).delegate('.form-control','change',function(event){ $.ajax({ url: '".yii\helpers\Url::toRoute( ...

Step-by-step guide to uploading files with Dredd using Swagger

I am trying to send the following data in my api.description.yml: parameters: - name: "file" in: "formData" required: true type: file description: fileupload consumes: - multipart/form-data; I am not certain about the ...

Issues with Materialize autocomplete drop-down functionality

I've been working on implementing materialize autocomplete in my project and have been facing issues with the dropdown not appearing. I tried using materialize version 0.98.2 from CDN as suggested, but it still doesn't seem to work. I suspect the ...

Tips for constructing a multi-dimensional entity from an existing object?

Looking to frame an object as a two-dimensional entity. let data = [ {'id':1, 'price':'12', 'price_type':'abc', 'mode':1, 'year':1}, {'id':1, 'pri ...

Learn how to use jQuery to load a text file containing arrays and then format them as

I'm attempting to load a .txt file containing multidimensional arrays using AJAX, and then sort through the data to display it on my website. However, I'm facing an issue where the data is only returning as plain text, even after trying to use JS ...

Make sure to include `jquery` in the types section of your tsconfig file

I've encountered an issue while trying to use jQuery in my Angular-TypeScript project. After installing jquery using "npm install @type/jquery", I am receiving the following error when trying to serve: Error TS2592: Cannot find name '$'. Is ...

Top technique for mirroring a website

Recently, I created a directory for a client's website. The site is fully operational, but the client would like a replicated version for testing and learning purposes. To create a full replica of his website, it will require hours of work to change ...

Direct your attention to the submit button

I've created a basic user login form where users can input their username and password, then press enter to search. The search results appear in a text box on the same page. My issue is with setting the focus on the submit button after entering the c ...

Express JS with multer is unable to process multiple file uploads, resulting in an empty array being

As I develop an app on Glitch with express js, the functionality requires users to upload multiple files. Here is the code snippet that I am using: var express = require('express'); var cors= require('cors'); var bodyParser= requir ...

Automatically omitting a selector that mimics a switch

After conducting thorough research, I discovered a variety of solutions using jQuery and Vanilla. While one answer perfectly addressed my issue, it failed to integrate effectively with the rest of my code. So, I decided to modify the code from this Stack O ...