We are going to divide or chunk the array into many smaller arrays or subarrays where each one is of a specified length size. We are going to view a couple of forms to that. for both cases the function chunk will receive two arguments, the first one will be the array to be chunked, the second is the size. If the remaining elements of an array is not equal to size, it still become a smaller chunk.


In the first way we will use two methods from the Array, the push and the slice . We will create an empty array to hold the chunks called chunked_array, and an index started at 0, while the index is less than length of the given array we are going to slice the array from index to size + index and push it into the chunked_array.

The index is very important in this implementation. Since the original array is not modified, the index needs to be updated to a correct position in the array. That is why it needs to be incremented with size after every iteration. Otherwise, we will enter an infinite loop.

const values = [1, 2, 3, 4, 5, 6, 7, 8, 9];

const chunk = (array, size) => {
  const chunked_array = [];
  let index = 0;
  
  while (index < array.length) {
    chunked_array.push(array.slice(index, size + index));
    index += size;
  }

  return chunked_array;
}

console.log(chunk(values, 3));
// expected output: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

console.log(chunk(values, 2));
// expected output: [[1, 2], [3, 4], [5, 6], [7, 8], [9]]

In the second way we will use two method from the Array, the from to create a new array, that fits the number of chunks that will be produced and the slice to map each element of the new array to a chunk the length of size. If the original array can’t be split evenly, the final chunk will contain the remaining elements.

We define the length of the new chunked_array by the length / size and then map each one of the subarrays with the slice() from index * size to index * size + size.

const values = [1, 2, 3, 4, 5, 6, 7, 8, 9];

const chunk = (array, size) =>
  Array.from({ length: Math.ceil(array.length / size) }, (v, index) =>
    array.slice(index * size, index * size + size)
  );

console.log(chunk(values, 3));
// expected output: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

console.log(chunk(values, 2));
// expected output: [[1, 2], [3, 4], [5, 6], [7, 8], [9]]