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

index.ts
function splitIntoChunks(arr: Array<any>, chunkSize: number): Array<Array<any>> {
  const chunks = [];
  let i = 0;

  while (i < arr.length) {
    chunks.push(arr.slice(i, i + chunkSize));
    i += chunkSize;
  }

  return chunks;
}

const originalArray = [1, 2, 3, 4, 5, 6, 7, 8, 9];
const result = splitIntoChunks(originalArray, 3);

console.log(result); // [[1,2,3],[4,5,6],[7,8,9]]
387 chars
17 lines

The splitIntoChunks function takes in two arguments: the array to be split and the desired size of each chunk. It then creates an empty array to hold the resulting chunks and sets an initial index variable to zero.

The function then enters a while loop that continues to slice segments from the input array and push them to the chunks array until the end of the array is reached. The size of each slice is determined by the chunkSize parameter passed to the function.

Once the while loop has completed executing, the function simply returns the chunks array with all the resulting chunks of the original array.

gistlibby LogSnag