Chunk Array

Easy~10 min

Given an array of numbers arr and a positive integer size, split the array into chunks where each chunk has at most size elements. Return the resulting 2D array.

The last chunk may contain fewer than size elements if the array length is not evenly divisible by size.

Examples

Example 1
Input: arr = [1, 2, 3, 4, 5], size = 2
Output: [[1, 2], [3, 4], [5]]
Explanation: The array is split into pairs. The last chunk has only one element because 5 is not divisible by 2.
Example 2
Input: arr = [1, 2, 3, 4], size = 4
Output: [[1, 2, 3, 4]]
Explanation: The entire array fits in one chunk.
Example 3
Input: arr = [1, 2, 3, 4, 5, 6], size = 3
Output: [[1, 2, 3], [4, 5, 6]]
Explanation: The array divides evenly into two chunks of size 3.

Constraints

  • 0 <= arr.length <= 10^4
  • 1 <= size <= arr.length (when arr is non-empty)
  • arr contains integers
Code
Ctrl+EnterRun|Ctrl+⇧+EnterSubmit
Output

Run your code to see results

Use Cmd+Enter to run