Split an array into chunks of a specified size
Quick Answer
The array chunk function divides a large array into smaller sub-arrays of a given size. It is the foundation for pagination, batch API requests, and grid-based UI rendering.
1function chunk(array, size) {
2 const chunks = [];
3 for (let i = 0; i < array.length; i += size) {
4 chunks.push(array.slice(i, i + size));
5 }
6 return chunks;
7}The array chunk function divides a large array into smaller arrays of a specified size. This is useful when you need to process data in batches, implement pagination, or organise data into groups for display purposes.
No. Array.slice returns a new array and does not modify the original.
You can use Array.from({ length: Math.ceil(arr.length / size) }, (_, i) => arr.slice(i * size, i * size + size)).
Yes. _.chunk(array, size) from lodash does the same thing.
This free javascript code snippet for array chunk is production-ready and copy-paste friendly. Whether you are building a web app, API, or frontend interface, this beginner-level example will help you implement array chunk quickly and correctly.
All snippets in the Snippetly library follow javascript best practices and are tested for real-world use. You can adapt this code to work with React, Vue, Node.js, or any project that uses javascript.
Organise your team's code snippets with Snippetly. Share knowledge and boost productivity across your organisation.