Use an array as the initial value. Calculate the chunk index: Math.floor(i / size). Push the element to acc[chunkIndex]: arr.reduce((acc, n, i) => { (acc[Math.floor(i / 3)] ||= []).push(n); return acc; }, []).
reduce Advanced Examples: Grouping and Pipelining in JavaScript
How do you chunk an array with reduce 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.