neiza
neiza

Reputation: 31

auto calculate total sum based on discount amounts

I'm doing some calculations of the total cost of items in an array that would be displayed in the HTML, the total sum should be such that when making the calculations, it should consider the discount amount against each row and add up together before it sums up all the rows total to make the total sum.

data

costItems = [
{
    name: 'Corn Flakes'
    unitPrice: 9,
    quantity: 10,
    hasDiscount: false,
    discountPercentage: 10
},
{
    name: 'Sugar'
    unitPrice: 5,
    quantity: 10,
    hasDiscount: true,
    discountPercentage: 10
},
{
    name: 'Bread'
    unitPrice: 2,
    quantity: 7,
    hasDiscount: false,
    discountPercentage: 0
},
{
    name: 'Salt'
    unitPrice: 1,
    quantity: 4,
    hasDiscount: false,
    discountPercentage: 0
}
]

Current Code I have

   calculateTotalSum() {
        this.totalSum = this.costItems.reduce((sum, {unitPrice, quantity}) => sum += unitPrice * quantity, 0);
console.log(this.totalSum)
      }

This works by calculating the total sum ignoring the discount amounts but what I want to do is to consider the discounts in there

Upvotes: 0

Views: 221

Answers (2)

Akshay Bande
Akshay Bande

Reputation: 2587

You can use Array.prototype.reduce.

let costItems = [{
    name: 'Corn Flakes',
    unitPrice: 9,
    quantity: 10,
    hasDiscount: false,
    discountPercentage: 10
  },
  {
    name: 'Sugar',
    unitPrice: 5,
    quantity: 10,
    hasDiscount: true,
    discountPercentage: 10
  },
  {
    name: 'Bread',
    unitPrice: 2,
    quantity: 7,
    hasDiscount: false,
    discountPercentage: 0
  },
  {
    name: 'Salt',
    unitPrice: 1,
    quantity: 4,
    hasDiscount: false,
    discountPercentage: 0
  }
];

let sum = costItems.reduce((acc, val) => acc += (val.quantity * val.unitPrice) * ((100 - val.discountPercentage) / 100), 0);

console.log(sum)

Upvotes: 1

Nikita Madeev
Nikita Madeev

Reputation: 4380

const costItems = [
    {
        name: 'Corn Flakes',
        unitPrice: 9,
        quantity: 10,
        hasDiscount: false,
        discountPercentage: 10,
    },
    {
        name: 'Sugar',
        unitPrice: 5,
        quantity: 10,
        hasDiscount: true,
        discountPercentage: 10,
    },
    {
        name: 'Bread',
        unitPrice: 2,
        quantity: 7,
        hasDiscount: false,
        discountPercentage: 0,
    },
    {
        name: 'Salt',
        unitPrice: 1,
        quantity: 4,
        hasDiscount: false,
        discountPercentage: 0,
    },
];

const totalSum = costItems.reduce(
    (sum, { unitPrice, quantity, discountPercentage }) =>
        (sum += unitPrice * quantity * (1 - discountPercentage / 100)),
    0,
);

console.log(totalSum);

Upvotes: 1

Related Questions