Can reduce be used for function composition in JavaScript?
Yes. 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.
Explore This Question
Search for additional explanations using these tools:
More FAQs in reduce in JavaScript: Examples and Use Cases
It combines all elements of an array into a single value using a callback (reducer) and an initial value. The callback receives an accumulator and each element, and returns the next accumulator. reduce returns the final accumulator.
Use an object as the initial value. For each element, add it to the array at acc[property]: people.reduce((acc, p) => { (acc[p.city] ||= []).push(p); return acc; }, {}).
Use an object as the initial value. For each element, increment the count: arr.reduce((acc, char) => { acc[char] = (acc[char] || 0) + 1; return acc; }, {}).
Still have questions?
Browse all our FAQs or reach out to our support team
