Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to split an array into chunks

Short answer

Step through the array by the chunk size and cut out parts with slice():

const chunk = (array, size) => {
  const result = [];
  for (let i = 0; i < array.length; i += size) {
    result.push(array.slice(i, i + size));
  }
  return result;
};
 
console.log(JSON.stringify(chunk([1, 2, 3, 4, 5, 6, 7], 3)));

Output:

[[1,2,3],[4,5,6],[7]]

With Array.from

First calculate the number of chunks, then build each of them:

const chunk = (array, size) =>
  Array.from({ length: Math.ceil(array.length / size) }, (_, i) => array.slice(i * size, i * size + size));
 
console.log(JSON.stringify(chunk(['a', 'b', 'c', 'd', 'e'], 2)));

Output:

[["a","b"],["c","d"],["e"]]

Common mistake

With a size of 0 the loop never ends, because the step is zero. Check the size before splitting:

const chunk = (array, size) => {
  if (size < 1) throw new Error('Size must be at least 1');
  const result = [];
  for (let i = 0; i < array.length; i += size) result.push(array.slice(i, i + size));
  return result;
};
 
try {
  chunk([1, 2, 3], 0);
} catch (error) {
  console.log(error.message);
}

Output:

Size must be at least 1

Functions used in this recipe

Thanks for reading!

Donate to the site — we work hard for you.