Reduce

πŸ‘¨β€πŸ’Ό The reduce method accumulates an array into a single value. It's the most powerful (and sometimes confusing) array methodβ€”and a cornerstone of functional programming.
const numbers = [1, 2, 3, 4]
const sum = numbers.reduce((acc, n) => acc + n, 0)
// 10
Parameters:
  • accumulator (acc) - The running total
  • current (n) - The current element
  • initial value (0) - Starting point
🐨 Open and:
  1. Use reduce to sum all prices
  2. Use reduce to find the most expensive product
  3. Use reduce to count products by category
πŸ’° Reduce syntax:
const result = array.reduce((accumulator, current) => newAccumulator, initial)
πŸ’° Counting by category (immutable pattern using spread):
const counts = products.reduce(
	(acc, p) => ({
		...acc,
		[p.category]: (acc[p.category] || 0) + 1,
	}),
	{} as Record<string, number>,
)
Each iteration returns a new object instead of mutating the accumulator. This is the functional approachβ€”easier to reason about and debug.

Please set the playground first

Loading "Reduce"
Loading "Reduce"

No tests here 😒 Sorry.