split a provided array into chunks of a provided size in typescript

You can split an array into chunks of a provided size in typescript by using the Array.from() method and a chunkSize parameter. The Array.from() method accepts a second parameter, which is a mapFn that can be used to transform each element in the array. We can use this to slice our desired chunk of the original array.

Here's the code:

index.ts
function chunkArray<T>(array: T[], chunkSize: number): T[][] {
  const chunks = Array.from({ length: Math.ceil(array.length / chunkSize) }, (_, index) =>
    array.slice(index * chunkSize, (index + 1) * chunkSize)
  );
  
  return chunks;
}

const arrayToChunk = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const chunkSize = 3;

const chunkedArray = chunkArray(arrayToChunk, chunkSize);

console.log(chunkedArray);
404 chars
15 lines

In this example, the chunkArray() function accepts an array to be chunked and a chunkSize parameter which specifies the size of each chunk. The Array.from() method is used to create a new array with a length corresponding to the number of chunks. The slice() method is then used to extract the desired chunk from the original array, and this chunk is inserted into the new array. Finally, the function returns the new array of chunks.

When executed, this code produces the following output:

index.ts
[ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ], [ 10 ] ]
50 chars
2 lines

As you can see, the original array has been split into chunks of size 3.

gistlibby LogSnag