Chunk Array

Splits an array into chunks of a specified size.

Contributed by @itsbrunodev

javascript
function chunkArray(array, size) {
  return Array.from({ length: Math.ceil(array.length / size) }, (_, i) =>
    array.slice(i * size, i * size + size)
  );
}
javascript
const numbers = [1, 2, 3, 4, 5, 6, 7];
chunkArray(numbers, 3); // [[1, 2, 3], [4, 5, 6], [7]]

Keywords

chunk
array
split