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
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)
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.