How do you chunk an array with reduce in JavaScript?
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; }, []).
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
