Home > database >  How to calculate discount for each item of an array using reduce()?
How to calculate discount for each item of an array using reduce()?

Time:05-27

I need to calculate 15% discount for each item in an array and the total.

Currently i have the solution for calculating and showing total discount for all items with reduce() method, but how do i calculate the discount for each item separately using reduce()? Is there a way to do that or should i use a different solution?

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>Корзина заказов</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 >
  <h1 >Корзина</h1>
  <section >
    <article >
      <img src="https://code.s3.yandex.net/web-code/entrance-test/jacket.png" alt="" >
      <div >
        <h2 >Have A Good Time x FA Two Tone куртка</h2>
        <p >Цвет: Зеленый/Оранжевый</p>
        <p >Размер: M</p>
        <p >Количество: 1</p>
      </div>
      <div >
        <p ><span >15890</span> руб.</p>
      </div>
    </article>
    <article >
      <img src="https://code.s3.yandex.net/web-code/entrance-test/vans.png" alt="" >
      <div >
        <h2 >Vans Old Skool кеды</h2>
        <p >Цвет: Черный/Белый</p>
        <p >Размер: 43</p>
        <p >Количество: 1</p>
      </div>
      <div >
        <p ><span >6390</span> руб.</p>
      </div>
    </article>
    <article >
      <img src="https://code.s3.yandex.net/web-code/entrance-test/pop-DRS.png" alt="" >
      <div >
        <h2 >Pop DRS Denim Stonewashed джинсы</h2>
        <p >Цвет: Голубой</p>
        <p >Размер: S</p>
        <p >Количество: 1</p>
      </div>
      <div >
        <p ><span >11290</span> руб.</p>
      </div>
    </article>
    <article >
      <img src="https://code.s3.yandex.net/web-code/entrance-test/by-parra.png" alt="" >
      <div >
        <h2 >By Parra ремень</h2>
        <p >Цвет: Мульти</p>
        <p >Размер: S</p>
        <p >Количество: 1</p>
      </div>
      <div >
        <p ><span >8550</span> руб.</p>
      </div>
    </article>
    <article >
      <img src="https://code.s3.yandex.net/web-code/entrance-test/board.png" alt="" >
      <div >
        <h2 >Fucking Awesome Drawings 2 Pink доска</h2>
        <p >Цвет: Розовый флюросентный</p>
        <p >Размер: Один размер</p>
        <p >Количество: 1</p>
      </div>
      <div >
        <p ><span >4790</span> руб.</p>
      </div>
    </article>
  </section>
  <section >
    <button >Использовать купон на 15%</button>
    <div >
      <h2 >Итого:</h2>
      <p ><span >46910</span> руб.</p>
    </div>
  </section>
  <script src="./task.js"></script>
  </body>
</html>

CodePudding user response:

While looping through the price items array, using reduce, you are already accessing each item and calculating the discounted price for each item. So before updating the reduce accumulator update the item value.

Update each item and add to 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);

And prevent discount from being applied again:

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;
}

CodePudding user response:

Something like

function getSingleValue(){

   var single = document.querySelector('.price-value').textContent;
   return single;

}

console.log(getSingleValue())

should give you an array with the individual prices from the html which you will then be able to use

  • Related