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

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.tsx
function chunkArray(arr, size) {
  return arr.reduce((acc, _, i) => (i % size) ? acc : [...acc, arr.slice(i, i + size)], []);
}

const arr = ['a', 'b', 'c', 'd', 'e', 'f'];
const size = 2;
const result = chunkArray(arr, size);
console.log(result); // Output: [['a', 'b'], ['c', 'd'], ['e', 'f']]
296 chars
9 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