TypeScript

Chunk Array Into Fixed-Size Pieces

admin by @admin ADMIN
Jun 16, 2026
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Split an array into chunks of `size` items. Common building block for batch APIs — "send 50 rows per request" — and for paginated grids.
TypeScript
Raw
export function chunk<T>(items: readonly T[], size: number): T[][] {
  if (size < 1) throw new Error('chunk size must be >= 1');
  const out: T[][] = [];
  for (let i = 0; i < items.length; i += size) {
    out.push(items.slice(i, i + size));
  }
  return out;
}

chunk([1, 2, 3, 4, 5, 6, 7], 3);   // [[1,2,3], [4,5,6], [7]]

// Bulk-send in batches of 50:
for (const batch of chunk(allRows, 50)) {
  await fetch('/api/bulk', { method: 'POST', body: JSON.stringify(batch) });
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.