Chunk Array
VerifiedSplits an array into groups of a given size, e.g. for batching API requests or building grids.
- array
- batch
- split
- pagination
Install
npx shadcn@latest add https://quicksnip.dev/r/chunk.jsonCode
/** Splits an array into groups of `size`. The last group holds the remainder. */
export function chunk<T>(items: readonly T[], size: number): T[][] {
if (!Number.isInteger(size) || size < 1) throw new RangeError("size must be a positive integer");
const result: T[][] = [];
for (let i = 0; i < items.length; i += size) result.push(items.slice(i, i + size));
return result;
}Usage
chunk([1, 2, 3, 4, 5], 2); // [[1, 2], [3, 4], [5]]