How do you use reduce for function composition (pipe) in JavaScript?
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.
Verify This Answer
Cross-check this information using these trusted sources:
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
