← All tasksJavaScript · Junior
chunk: split an array into pieces
Write a function chunk(array, size) that splits an array into subarrays of length size. The last piece may be shorter.
For example, chunk([1, 2, 3, 4, 5], 2) returns [[1, 2], [3, 4], [5]]. Don't modify the original array.
Ctrl+Enter runs the tests. Tab indents; to leave the editor with the keyboard, press Esc and then Tab. Your code is saved in this browser.
Tests (5)
expect(chunk([1, 2, 3, 4, 5], 2)).toEqual([[1, 2], [3, 4], [5]]);
expect(chunk([1, 2, 3], 3)).toEqual([[1, 2, 3]]);
expect(chunk([1, 2], 5)).toEqual([[1, 2]]);
expect(chunk([], 2)).toEqual([]);
const source = [1, 2, 3]; chunk(source, 2); expect(source).toEqual([1, 2, 3]);