← 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.

Tests (5)

  1. expect(chunk([1, 2, 3, 4, 5], 2)).toEqual([[1, 2], [3, 4], [5]]);
  2. expect(chunk([1, 2, 3], 3)).toEqual([[1, 2, 3]]);
  3. expect(chunk([1, 2], 5)).toEqual([[1, 2]]);
  4. expect(chunk([], 2)).toEqual([]);
  5. const source = [1, 2, 3];
    chunk(source, 2);
    expect(source).toEqual([1, 2, 3]);