Use an array of functions as the initial value: fns.reduce((acc, fn) => fn(acc), x). This applies each function in sequence to the accumulator. This is the basis of the pipe pattern.
reduce Advanced Examples: Grouping and Pipelining in JavaScript
How do you use reduce for function composition (pipe) in JavaScript?
The answer
More FAQs in reduce Advanced Examples: Grouping and Pipelining in JavaScript
Use an object as the initial value. For each element, push it to the array at acc[property]: people.reduce((acc, p) => { (acc[p.dept] ||= []).push(p); return acc; }, {}).
Use an object as the initial value. For each element, increment the count: arr.reduce((acc, w) => { acc[w] = (acc[w] || 0) + 1; return acc; }, {}).
Use an object as the initial value. For each element, set acc[element.id] = element: users.reduce((acc, u) => { acc[u.id] = u; return acc; }, {}). This gives O(1) lookup by id.
Still have questions?
Browse all our FAQs or reach out to our support team
Want to upskill yourself?
Your learning library
Small steps. Big possibilities.
Find your next course. Build something great.