split an array of generics into chunks of size n in typescript

To split an array of generics into chunks of size n, we can create a generic function that takes in an array of any type and a number for chunk size, then returns an array of arrays with each inner array containing the specified number of elements.

Here's the code for the function:

index.ts
function chunkArray<T>(arr: T[], chunkSize: number): T[][] {
  const chunks = [];
  let i = 0;
  while (i < arr.length) {
    chunks.push(arr.slice(i, i + chunkSize));
    i += chunkSize;
  }
  return chunks;
}
211 chars
10 lines

This function uses a loop to iterate over the input array and slice it into smaller arrays of size chunkSize. The results are pushed into a new array, which is returned at the end.

To use this function, simply pass in your array and the desired chunk size:

index.ts
const arrayToChunk = [1, 2, 3, 4, 5, 6, 7, 8, 9];
const chunkedArray = chunkArray(arrayToChunk, 3);
console.log(chunkedArray); // [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
164 chars
4 lines

This will output an array of arrays, with each inner array containing three elements.

gistlibby LogSnag