const items = [
{ id: 1, name: 'Apple', price: 0.5 },
{ id: 2, name: 'Banana', price: 0.3 },
{ id: 3, name: 'Orange', price: 0.6 }
];
function applyDiscount(items, discount) {
for (let i = 0; i < items.length; i++) {
items[i].price -= items[i].price * discount;
items[i].price = items[i].price.toFixed(2);
}
return items;
}
const discountedItems = applyDiscount(items, 0.1);
const totalPrice = discountedItems.reduce((sum, item) => sum + item.price, 0);
The bug is in the applyDiscount function.
After applying the discount, we use toFixed(2) to round the price to two decimal places. However, toFixed() returns a string, not a number. This means that when we later try to calculate the total price using reduce(), we’re actually performing string concatenation instead of number addition.
There are a bunch of ways to fix this. The simplest (if you’re confident in your data), is to use Number.
function applyDiscount(items, discount) {
return items.map(item => ({
...item,
price: Number((item.price * (1 - discount)).toFixed(2))
}));
}