Reduce
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 use the provided
products fixture:- Create
totalwithreduceβ sum of all prices, starting from0(expected1579.95) - Create
mostExpensivewithreduceβ the product object with the highest price (expected name'Laptop', price999.99) - Create
countByCategorywithreduceβ an object of category counts (expected{ Electronics: 3, Kitchen: 2 }) - Export
total,mostExpensive, andcountByCategory
π°
reduce combines all items into one accumulated result.π° When counting with an object accumulator, you can either update a single
object or return a new object each step β choose the approach you find clearer.