Reduce

Reduce
πŸ‘¨β€πŸ’Ό Excellent! You've tackled reduce, the most versatile array method.
πŸ¦‰ reduce can do almost anything, but that doesn't mean you should use it for everything. Often map + filter is clearer:
// Using reduce (clever but harder to read)
const total = products.reduce((sum, p) => (p.inStock ? sum + p.price : sum), 0)

// Using filter + reduce (clearer intent)
const total = products
	.filter((p) => p.inStock)
	.reduce((sum, p) => sum + p.price, 0)
Use reduce when you need:
  • Sums/averages
  • Finding min/max
  • Grouping/counting
  • Building objects from arrays
Immutable vs mutable accumulators: We used the spread pattern ({ ...acc, [key]: value }) which creates a new object each iteration. This is easier to reason about and is the functional approach. For very large arrays (thousands of items), mutating the accumulator directly is faster. Pragmatism winsβ€”choose based on your actual data size and readability needs.

Please set the playground first

Loading "Reduce"
Loading "Reduce"
Login to get access to the exclusive discord channel.
Loading Discord Posts