To split a provided array into chunks of provided size in JavaScript, we can use the array.reduce() method. The reduce()
method applies a function against an accumulator and each element in the array to reduce it to a single value. We can use this method to create a new array of chunks, where each chunk's size is equal to the provided size.
Here is an example code snippet that splits an array into chunks:
index.tsx296 chars9 lines
In the above code, chunkArray()
function accepts two arguments - an array and chunk size. The reduce()
method accumulates the chunks into an empty array. i % size
checks if the current index i
is a multiple of the provided size. If it is not, the function returns the accumulated array without adding any chunk. If it is, the function adds the current chunk to the array.
We can use the chunkArray()
function to split any array into chunks of a provided size.
gistlibby LogSnag