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.ts404 chars15 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.ts50 chars2 lines
As you can see, the original array has been split into chunks of size 3.
gistlibby LogSnag