Use .reduce() to accumulate array values into a single result
const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((acc, num) => acc + num, 0);
console.log(sum); // 15const cart = [
{ item: 'Apple', price: 1.5, qty: 3 },
{ item: 'Bread', price: 2.5, qty: 1 },
{ item: 'Milk', price: 3.0, qty: 2 }
];
const total = cart.reduce((sum, product) => {
return sum + (product.price * product.qty);
}, 0);
console.log(total);const grouped = items.reduce((acc, item) => {
const key = item.category;
acc[key] = acc[key] || [];
acc[key].push(item);
return acc;
}, {});const counts = arr.reduce((acc, val) => {
acc[val] = (acc[val] || 0) + 1;
return acc;
}, {});Avoid manual accumulation with loops
// DON'T DO THIS
var sum = 0;
for (var i = 0; i < numbers.length; i++) {
sum += numbers[i];
}✓ Works in all modern browsers (ES5+)