Jump to the editorJAVASCRIPT
JAVASCRIPT JAVASCRIPT JAVASCRIPT
4.1. Split an array into chunks
Easy
Topics
This question is in
4. Array utilitiesA 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
function chunk(array, size) // returns an array of arraysarray: the items to split. It is not changed.size: how many items go in each group. A missingsizecounts as1.- Returns a new array. Every group is a new array, even when one group holds every item.
Requirements
- Every group has exactly
sizeitems, except the last one, which holds the leftover items. - A
sizeat least as large as the array gives one group with every item. - An empty array gives
[]. - A missing
sizecounts as1. - A fractional
sizeis rounded down:2.7means2. - A
sizebelow1(including0, negative numbers andNaN) gives[], and never loops forever. - The input array is not changed, and no group is the input array itself.
- Items are kept as they are: the same objects, and
undefinedornullitems too. - It handles 100,000 items quickly.
Examples
chunk([1, 2, 3, 4, 5], 2); // [[1, 2], [3, 4], [5]]
chunk(["a", "b", "c"]); // [["a"], ["b"], ["c"]]chunk([1, 2, 3], 10); // [[1, 2, 3]]
chunk([1, 2, 3, 4, 5], 2.7); // [[1, 2], [3, 4], [5]]chunk([1, 2, 3], 0); // []
chunk([], 3); // []Environment
- Plain JavaScript in a browser page; the tests call the global
chunkfromchunk.js. - Any built-in may be used. The tests only pass arrays without holes.
Hints
- Where does each group start? How far apart are those starting points?
- Which array method copies a range of items without changing the array?
- What does a loop that moves forward by
0each 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…