Skip to curriculum
Jump to the editor

4.1. Split an array into chunks

Easy
Topics

This question is in

4. Array utilities
10–15 min

A product grid shows four cards per row. A bulk API accepts at most 100 ids per request. A chat app sends messages in batches of 20. Each time, one long list has to be cut into groups of a fixed size, and the last group gets whatever is left.

Write chunk(array, size) in chunk.js. It returns a new array of groups, each group a new array of up to size items, in the original order.

Signature

JAVASCRIPT
function chunk(array, size) // returns an array of arrays
  • array: the items to split. It is not changed.
  • size: how many items go in each group. A missing size counts as 1.
  • Returns a new array. Every group is a new array, even when one group holds every item.

Requirements

  1. Every group has exactly size items, except the last one, which holds the leftover items.
  2. A size at least as large as the array gives one group with every item.
  3. An empty array gives [].
  4. A missing size counts as 1.
  5. A fractional size is rounded down: 2.7 means 2.
  6. A size below 1 (including 0, negative numbers and NaN) gives [], and never loops forever.
  7. The input array is not changed, and no group is the input array itself.
  8. Items are kept as they are: the same objects, and undefined or null items too.
  9. It handles 100,000 items quickly.

Examples

JAVASCRIPT
chunk([1, 2, 3, 4, 5], 2);   // [[1, 2], [3, 4], [5]]
chunk(["a", "b", "c"]);      // [["a"], ["b"], ["c"]]
JAVASCRIPT
chunk([1, 2, 3], 10);        // [[1, 2, 3]]
chunk([1, 2, 3, 4, 5], 2.7); // [[1, 2], [3, 4], [5]]
JAVASCRIPT
chunk([1, 2, 3], 0);         // []
chunk([], 3);                // []

Environment

  • Plain JavaScript in a browser page; the tests call the global chunk from chunk.js.
  • Any built-in may be used. The tests only pass arrays without holes.

Hints

  1. Where does each group start? How far apart are those starting points?
  2. Which array method copies a range of items without changing the array?
  3. What does a loop that moves forward by 0 each time do?

The explanation comes with the course

A walkthrough of every line of a solution, the mistakes the tests catch, other ways to write it, and links to the lessons that teach each idea.

  • Every line explained
  • The mistakes each test catches
  • Links to the lessons behind it
Back to the question
Loading the editor…