Skip to the code
cf.

Chunk an array

Write chunk(array, size). It returns a new array of groups: the first size items of array, then the next size items, and so on. The last group holds whatever is left, so it can be shorter.

size must be a positive integer. For anything else, such as 0, -1, 1.5, or NaN, throw a RangeError.

An empty array gives []. Every group is a new array holding the same items as array, and array itself never changes.

chunk([1, 2, 3, 4, 5], 2); // [[1, 2], [3, 4], [5]]
chunk([1, 2, 3, 4], 2);    // [[1, 2], [3, 4]]
chunk([1, 2, 3], 5);       // [[1, 2, 3]]
chunk([], 3);              // []
chunk([1, 2], 0);          // throws a RangeError

What the tests check

  1. splits the array into groups of size items
    expect(chunk([1, 2, 3, 4, 5, 6], 3)).toEqual([[1, 2, 3], [4, 5, 6]]);
    expect(chunk(["a", "b", "c"], 1)).toEqual([["a"], ["b"], ["c"]]);
    
  2. puts the leftovers in a shorter last group
    expect(chunk([1, 2, 3, 4, 5], 2)).toEqual([[1, 2], [3, 4], [5]]);
    
  3. never adds an empty group at the end
    const groups = chunk([1, 2, 3, 4], 2);
    expect(groups).toHaveLength(2);
    expect(groups).toEqual([[1, 2], [3, 4]]);
    
  4. gives one group when size is larger than the array
    expect(chunk([1, 2, 3], 5)).toEqual([[1, 2, 3]]);
    
  5. returns an empty array for an empty array
    expect(chunk([], 3)).toEqual([]);
    
  6. throws a RangeError when size isn't a positive integer
    for (const size of [1.5, NaN, -1, 0]) {
      let thrown;
      try {
        chunk([1, 2], size);
      } catch (error) {
        thrown = error;
      }
      // The page stops a loop that never ends with an InfiniteLoopError, which is a RangeError too, so report it here.
      if (thrown?.name === "InfiniteLoopError") throw new Error("chunk([1, 2], " + size + ") never finished: " + thrown.message);
      expect(thrown).toBeInstanceOf(RangeError);
    }
    
  7. returns new groups and leaves the array alone
    const item = { id: 1 };
    const input = [item, 2, 3];
    const groups = chunk(input, 5);
    expect(groups[0]).not.toBe(input);
    expect(groups[0][0]).toBe(item);
    chunk(input, 2);
    expect(input).toEqual([{ id: 1 }, 2, 3]);
    expect(input).toHaveLength(3);
    

Learn more

solution.jsSaved in this browser

Run tests runs every test on your code, here in your browser. The problem is solved when they all pass.

Ctrl + Enter runs the tests (⌘ + Enter on a Mac).