typescript / intermediate
Snippet
Splitting Collections into Uniform Chunks with Array.from
Using Array.from with an object possessing a length property allows clean allocation of chunked multi-dimensional arrays without manual loops or side effects.
snippet.ts
typescript
1
2
3
4
5
6
7
8
9
10
function chunkArray<T>(items: T[], chunkSize: number): T[][] {const length = Math.ceil(items.length / chunkSize);return Array.from({ length }, (_, index) => {const start = index * chunkSize;return items.slice(start, start + chunkSize);});}const numbers = [1, 2, 3, 4, 5, 6, 7];const chunked = chunkArray(numbers, 3);
Breakdown
1
function chunkArray<T>(items: T[], chunkSize: number): T[][] {
Generic signature ensuring strong typing for array elements and nested output.
2
const length = Math.ceil(items.length / chunkSize);
Calculates the total number of sub-array groups required.
3
return Array.from({ length }, (_, index) => {
Creates a new array of specific length and initializes elements using a mapping callback.