Skip to content
jshacks.dev
Functions

Implement chunk From Scratch in JavaScript

Write chunk from scratch in JavaScript, split arrays into fixed-size groups, handle bad sizes and short last groups, add a lazy generator and tests. Node.js 24.

7 min read
Summarize in AI
Flat illustration of items passing through a chain of collection methods, with the JavaScript, Vite, TypeScript and Node.js logos.

"Split this array into groups of three" sounds like a ten-second question, and it is one until the interviewer asks what happens when the size is 0, when the array length is not a multiple of the size, or when the input is a million items long. A good answer writes the loop, names those three cases out loud and then chooses what to do about each. This post builds chunk from scratch on Node.js 24, shows the version most candidates write first and where it breaks, adds a lazy generator for big inputs and ends with tests.

The contract

State the contract before the code. chunk(items, size) returns an array of arrays. Every inner array has exactly size items, except possibly the last, which holds whatever is left. The order is preserved, the input is not modified and an empty input returns an empty array, not [[]].

Then ask the question that shows judgment: what is a valid size? A positive integer. Everything else, 0, a negative number, 1.5, NaN, is a caller bug, and the function should say so instead of looping forever or returning nonsense.

The first version: a slice loop

The shortest correct version walks the array in steps of size and slices.

JavaScript
function chunk(items, size) {
  const result = [];

  for (let i = 0; i < items.length; i += size) {
    result.push(items.slice(i, i + size));
  }

  return result;
}

console.log(chunk([1, 2, 3, 4, 5, 6, 7], 3));
console.log(chunk([], 3));
console.log(chunk(["a", "b"], 5));
Text
[ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7 ] ]
[]
[ [ 'a', 'b' ] ]

This is the answer to give first. slice never reads past the end of the array, so the short last group needs no special case, and the empty input never enters the loop. The array is not changed, because slice returns a copy.

Where it breaks

The loop trusts size. Try the values a careless caller passes.

JavaScript
console.log(chunk([1, 2, 3], 1.5));
Text
[ [ 1, 2 ], [ 2, 3 ], [ 3 ] ]

With 1.5, the index moves 0, 1.5, 3, and slice truncates its arguments to integers, so the groups overlap and the output is wrong without any error. A negative size is worse, because i moves away from items.length and the loop condition stays true forever.

The same hang happens with 0.

JavaScript
function badChunk(items, size) {
  const result = [];
  for (let i = 0; i < items.length; i += size) {
    result.push(items.slice(i, i + size));
  }
  return result;
}

// badChunk([1, 2, 3], 0) never returns:
// i stays 0, so the loop condition is always true
// and result grows until the process runs out of memory.

An infinite loop that allocates on every pass is the failure to name in an interview. It does not throw, it does not log, and in a Node.js server it blocks the event loop until the process is killed.

Validating the size

Reject anything that is not a positive integer, with an error that names the value.

JavaScript
function chunk(items, size) {
  if (!Number.isInteger(size) || size < 1) {
    throw new RangeError(`chunk size must be a positive integer, got ${size}`);
  }

  const result = [];

  for (let i = 0; i < items.length; i += size) {
    result.push(items.slice(i, i + size));
  }

  return result;
}

for (const bad of [0, -1, 1.5, NaN, "2"]) {
  try {
    chunk([1, 2, 3], bad);
  } catch (error) {
    console.log(error.message);
  }
}
Text
chunk size must be a positive integer, got 0
chunk size must be a positive integer, got -1
chunk size must be a positive integer, got 1.5
chunk size must be a positive integer, got NaN
chunk size must be a positive integer, got 2

The last line is worth a sentence. Number.isInteger("2") is false, because it does not coerce, so the string "2" is rejected, and the message prints 2 because the template literal converts it. If you want the function to accept numeric strings, that is a decision, and the strict answer is usually better: the caller who passes "2" from a query string should convert it on purpose.

RangeError is the right class. It is the built-in error for a value outside its allowed range, which is exactly this.

A version without slice

Interviewers sometimes ask for a second approach to see whether you understand what slice hides. The manual version builds each group by pushing into the current one.

JavaScript
function chunkManual(items, size) {
  if (!Number.isInteger(size) || size < 1) {
    throw new RangeError(`chunk size must be a positive integer, got ${size}`);
  }

  const result = [];
  let current = [];

  for (const item of items) {
    current.push(item);

    if (current.length === size) {
      result.push(current);
      current = [];
    }
  }

  if (current.length > 0) {
    result.push(current);
  }

  return result;
}

console.log(chunkManual([1, 2, 3, 4, 5], 2));
Text
[ [ 1, 2 ], [ 3, 4 ], [ 5 ] ]

The final if is the part people forget. Without it, a length that is not a multiple of size silently drops the last group, and the output would be [ [ 1, 2 ], [ 3, 4 ] ]. The advantage of this version is that it works on any iterable, because for...of does not need length or indexing, which leads to the next step.

Chunking any iterable lazily

The slice version needs an array in memory, and it builds the whole result before returning. For a large or unbounded source, a generator produces one group at a time.

JavaScript
function* chunkLazy(iterable, size) {
  if (!Number.isInteger(size) || size < 1) {
    throw new RangeError(`chunk size must be a positive integer, got ${size}`);
  }

  let current = [];

  for (const item of iterable) {
    current.push(item);

    if (current.length === size) {
      yield current;
      current = [];
    }
  }

  if (current.length > 0) {
    yield current;
  }
}

function* naturals() {
  let n = 1;
  while (true) {
    yield n++;
  }
}

const groups = chunkLazy(naturals(), 3);

console.log(groups.next().value);
console.log(groups.next().value);
console.log(chunkLazy("abcde", 2).toArray());
Text
[ 1, 2, 3 ]
[ 4, 5, 6 ]
[ [ 'a', 'b' ], [ 'c', 'd' ], [ 'e' ] ]

Two things happen here. The source naturals() never ends, yet the function returns the first group after reading only three values, because a generator runs only when asked. And a string is an iterable of characters, so chunkLazy("abcde", 2) works with no extra code. The .toArray() call is an iterator helper, available on generator objects since Node.js 22, which turns the lazy sequence into an array when you do want all of it.

One detail to point out: the validation inside a generator function does not run when you call it. The body starts on the first next(), so chunkLazy([], 0) returns an iterator without complaint and throws on the first read. If you want an immediate error, split the function in two: an ordinary outer function validates and returns the inner generator.

What about the input being modified later

Both slice and the manual version copy references, not values. For an array of numbers that does not matter. For an array of objects, each group holds the same objects as the input, so changing groups[0][0].name changes the original item.

JavaScript
const users = [{ name: "Ada" }, { name: "Linus" }, { name: "Grace" }];
const groups2 = chunk(users, 2);

groups2[0][0].name = "Changed";

console.log(users[0].name);
console.log(groups2[0][0] === users[0]);
Text
Changed
true

That is the expected behavior for a shallow operation, and the answer is to say so. A deep copy is a separate concern, and a chunk that quietly cloned every item would be slower and surprising.

Where chunking is used in real code

Chunking is rarely the goal. It is the step before something else, and naming the use shows you have shipped it. The most common is batching writes: a database accepts a limited number of rows or parameters in one statement, so a list of ten thousand records is split into groups of five hundred and inserted one group at a time. The second is rate-limited APIs, where a provider allows a fixed number of items per request and you send them in sequence. The third is rendering, where a long list is shown in pages or rows of a grid.

The trap in all three is the same. Splitting is cheap, but what you do with each group is not, and Promise.all(chunk(items, 100).map(send)) starts every group at once, which defeats the point of chunking. Process the groups in a loop with await when order or load matters, and reach for a pool only when you need a fixed number in flight. Say that in the interview and the question stops being about arrays and becomes about systems, which is where the interviewer usually wants to go.

A last detail concerns the choice between a fixed size and a fixed count. "Groups of three" and "three groups" are different functions. The second needs the size computed first, as Math.ceil(items.length / count), and then the same loop. Asking which one the caller means is a good clarifying question before writing any code.

Testing it

Test the behaviors you promised, including the failure.

JavaScript
import test from "node:test";
import assert from "node:assert/strict";

test("chunk splits and keeps the remainder", () => {
  assert.deepEqual(chunk([1, 2, 3, 4, 5], 2), [[1, 2], [3, 4], [5]]);
});

test("chunk returns an empty array for empty input", () => {
  assert.deepEqual(chunk([], 3), []);
});

test("chunk does not modify the input", () => {
  const input = [1, 2, 3];
  chunk(input, 2);
  assert.deepEqual(input, [1, 2, 3]);
});

test("chunk rejects a bad size", () => {
  assert.throws(() => chunk([1], 0), RangeError);
  assert.throws(() => chunk([1], 1.5), RangeError);
});
Text
ℹ tests 4
ℹ pass 4
ℹ fail 0

How to finish the interview answer

Close with the decisions rather than the code. You validated size because 0 would loop forever. You kept the short last group because dropping data silently is worse than an uneven group. You returned copies of the groups and kept the items shared. And you offered a generator version for sources that are large or infinite. If asked about the standard library, mention that JavaScript has no built-in chunk: Lodash ships _.chunk, and the language has had no array method for it, so writing it yourself is normal and takes six lines.

Taggedinterview
Share

Keep reading

Flat illustration of two options weighed side by side, with the JavaScript, Vite and Node.js logos.
Functions

Classes vs Factory Functions

Classes vs factory functions in JavaScript compared on private state, this, instanceof, inheritance, memory, JSON and testing, with exact output.

7 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.