Emmanuel Akinfulubi

JavaScriptArray

Chunk an array into rows of a fixed size in JavaScript

Intermediate · 4 min read

Chunking means cutting one long list into rows of the same size. A photo gallery shows three pictures per row. A results page shows ten items per page. A bulk upload sends records in batches of fifty. Each time, the code takes a flat list and splits it into smaller lists.

In this tutorial you will write a function called chunk that turns [1, 2, 3, 4, 5] into [[1, 2], [3, 4], [5]]. You will decide what happens to the leftover item, and you will stop the function from freezing the page when the size is zero. You should know arrays, for loops and functions.

How slice cuts a window

slice(start, end) copies part of an array. It includes start and stops just before end, and it never changes the array you call it on.

JavaScript

const xs = [1, 2, 3, 4, 5];
console.log(xs.slice(0, 2)); // [ 1, 2 ]
console.log(xs.slice(2, 4)); // [ 3, 4 ]
console.log(xs.slice(4, 6)); // [ 5 ]

Look at the last line. There is no index 5, but slice doesn't complain. It just stops at the end of the array. That is called clamping, and it will save us a special case later.

Stepping by more than one

Most loops add one to i each time. A loop can step by any amount. If i jumps forward by the row size, it lands on the start of each row: 0, 2, 4.

JavaScript

for (let i = 0; i < 5; i += 2) console.log(i); // prints 0, then 2, then 4

Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.

21 Chunk a list into rows

fair

Split [1, 2, 3, 4, 5] into rows of two. Decide what to do with the remainder, and what to do when the size is zero.

Stuck? Three hints, smallest first
  1. 1. Step the index forward by size rather than by one, and slice each window.
  2. 2. slice clamps, so the last row comes out short with no special case.
  3. 3. A size of zero would step nowhere and loop forever. Refuse it.

Step 1: the loop that builds rows

Put the two ideas together. Step i forward by size, and slice one window at each stop.

Step 1

function chunk(xs, size) {
  const rows = [];
  for (let i = 0; i < xs.length; i += size) rows.push(xs.slice(i, i + size));
  return rows;
}
console.log(chunk([1, 2, 3, 4], 2));    // [ [ 1, 2 ], [ 3, 4 ] ]
console.log(chunk([1, 2, 3, 4, 5], 2)); // [ [ 1, 2 ], [ 3, 4 ], [ 5 ] ]

When the list divides evenly, every row is full. When it doesn't, the last row is shorter. You didn't write any code for that: slice(4, 6) simply returns [5] because it clamps.

A short last row is the usual choice. A gallery shows two pictures on its last line rather than hiding them.

Step 2: the edge cases

Step 2

function chunk(xs, size) {
  const rows = [];
  for (let i = 0; i < xs.length; i += size) rows.push(xs.slice(i, i + size));
  return rows;
}
console.log(chunk([1, 2], 9)); // [ [ 1, 2 ] ]
console.log(chunk([], 3));     // []

A size bigger than the list gives one row with everything in it. An empty list gives no rows at all, because the loop condition 0 < 0 is false straight away.

Step 3: the size that never moves

Now the wrong turn. What does chunk([1, 2], 0) do with the Step 1 code? The loop adds 0 to i every time, so i stays at 0 forever. The condition 0 < 2 is always true, and the loop keeps pushing empty rows until the program runs out of memory. Don't run that one.

This is not just a typing mistake. The size often comes from a web address, like ?perPage=0, or from a setting someone typed in. You need to refuse bad sizes before the loop starts.

Step 3

function chunk(xs, size) {
  if (!Number.isInteger(size) || size < 1) throw new RangeError('size must be a positive integer');
  const rows = [];
  for (let i = 0; i < xs.length; i += size) rows.push(xs.slice(i, i + size));
  return rows;
}
try {
  chunk([1, 2], 0);
} catch (e) {
  console.log(e.constructor.name); // RangeError
}

Number.isInteger(size) is true only for whole numbers, so it rejects 1.5 and NaN. size < 1 rejects 0 and negative numbers. One line covers every bad size. A RangeError is JavaScript's built-in error for "this number is outside the allowed range".

Step 4: the same thing without a loop

You can also work out how many rows there will be, then build each one. Math.ceil rounds up, so 5 items in rows of 2 gives Math.ceil(2.5), which is 3 rows.

Step 4

const chunkFrom = (xs, size) =>
  Array.from({ length: Math.ceil(xs.length / size) }, (_, i) => xs.slice(i * size, i * size + size));
console.log(chunkFrom([1, 2, 3, 4, 5], 2)); // [ [ 1, 2 ], [ 3, 4 ], [ 5 ] ]

Array.from({ length: 3 }, fn) makes an array of 3 items by calling fn with each index. Row i starts at i * size. The _ is a name for the first argument, which we don't need.

Step 5: undoing it, and what gets copied

Step 5

function chunk(xs, size) {
  const rows = [];
  for (let i = 0; i < xs.length; i += size) rows.push(xs.slice(i, i + size));
  return rows;
}
console.log(chunk([1, 2, 3, 4, 5], 2).flat()); // [ 1, 2, 3, 4, 5 ]
const record = { id: 1 };
console.log(chunk([record], 1)[0][0] === record); // true

flat() joins the rows back into one list, so chunking loses nothing. The second check shows that the rows are new arrays, but the items inside are the same objects, not copies. That is called a shallow copy, and it is what you want: chunking a thousand records should not copy a thousand records.

The full solution

The panel has the guarded chunk, the loop-free chunkFrom, and a run through every case above. Press Run and look at the short last row and the refused size of zero.

The answer

function chunk(xs, size) {
  if (!Number.isInteger(size) || size < 1) throw new RangeError('size must be a positive integer');
  const rows = [];
  for (let i = 0; i < xs.length; i += size) rows.push(xs.slice(i, i + size));
  return rows;
}

// The same thing without a loop: work out the row count, then build it.
const chunkFrom = (xs, size) =>
  Array.from({ length: Math.ceil(xs.length / size) }, (_, i) => xs.slice(i * size, i * size + size));

const record = { id: 1 };
const rowsOfObjects = chunk([record], 1);

const refused = (() => {
  try { chunk([1, 2], 0); return 'no error'; } catch (e) { return e.constructor.name; }
})();

console.log('exact fit    :', chunk([1, 2, 3, 4], 2));
console.log('a remainder  :', chunk([1, 2, 3, 4, 5], 2), '<- short last row');
console.log('size > length:', chunk([1, 2], 9));
console.log('empty        :', chunk([], 3));
console.log('size of 0    :', refused);
console.log('flat() undoes it:', chunk([1, 2, 3, 4, 5], 2).flat());

Output


      
9 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 9 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

9 checks

test('an exact fit', chunk([1, 2, 3, 4], 2), [[1, 2], [3, 4]]);
test('a remainder becomes a shorter final row', chunk([1, 2, 3, 4, 5], 2), [[1, 2], [3, 4], [5]]);
test('a size larger than the list gives one row', chunk([1, 2], 9), [[1, 2]]);
test('an empty list gives no rows at all', chunk([], 3), []);
test('the loop-free version agrees', chunkFrom([1, 2, 3, 4, 5], 2), chunk([1, 2, 3, 4, 5], 2));
test('flat() puts it back together', chunk([1, 2, 3, 4, 5], 2).flat(), [1, 2, 3, 4, 5]);
test('the rows are new arrays, so the source is untouched', chunk([1, 2], 1).length, 2);
test('but the elements are shared, not cloned', rowsOfObjects[0][0] === record, true);
test('a size of zero is refused instead of hanging', refused, 'RangeError');

Also Basic 44. The angle here is the guard. chunk(xs, 0) written the obvious way never advances i, so it allocates rows until the tab dies — the sort of bug that only shows up when a page size arrives from a query string. Number.isInteger rejects 0, -1, 1.5 and NaN in one condition.

The rows are fresh arrays but the elements inside them are the same objects, which the object assertion pins down. That is what "shallow" means, and it is what you want here: chunking a thousand records should not clone a thousand records.

Common mistakes

  • Not checking the size. A size of zero makes the loop run forever. Check it before the loop.
  • Stepping by one. With i++ instead of i += size, you get overlapping windows like [1, 2], [2, 3], [3, 4].
  • Adding a special case for the last row. slice already clamps at the end of the array, so the short row comes out on its own.

Try it yourself

  1. Split the letters of 'abcdefg' into groups of three. (Hint: turn the string into an array first.)
  2. Write pageOf(xs, size, page) that returns just one page, where page 1 is the first row.
  3. Change chunk so that it pads the last row with null until it is full.

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.