Back to Home
Arrays

How to Reduce Arrays to Single Values

Use .reduce() to accumulate array values into a single result

Quick Answer (2024 ES6+ Way)

javascript
const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((acc, num) => acc + num, 0);
console.log(sum); // 15

Live Example

javascript
const 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);

Common Variations

Group By Property
javascript
const grouped = items.reduce((acc, item) => {
  const key = item.category;
  acc[key] = acc[key] || [];
  acc[key].push(item);
  return acc;
}, {});
Count Occurrences
javascript
const counts = arr.reduce((acc, val) => {
  acc[val] = (acc[val] || 0) + 1;
  return acc;
}, {});

❌ Don't Do This (Outdated Way)

Avoid manual accumulation with loops

javascript
// DON'T DO THIS
var sum = 0;
for (var i = 0; i < numbers.length; i++) {
  sum += numbers[i];
}

Browser Support

Works in all modern browsers (ES5+)

#reduce#array#accumulate