Reputation: 31
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
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
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