coding round · ~8 min
JavaScriptbeginner

Chunk an array

Write chunk(arr, size) that splits arr into groups of size items. The last group holds whatever is left over.

  • chunk([1, 2, 3, 4], 2) → [[1, 2], [3, 4]]
  • chunk([1, 2, 3, 4, 5], 2) → [[1, 2], [3, 4], [5]]
  • chunk([1, 2, 3], 10) → [[1, 2, 3]]
  • chunk([1, 2, 3], 0) → []

Return [] for an empty array or when size is less than 1, and leave the input array untouched.

Define chunk in the editor. 7 tests will call it.

solution.js
function chunk(arr, size) {
  // Split arr into arrays of `size` items each.
  // The last chunk may be shorter. Return [] if size < 1.
}

Tests⌘/Ctrl + Enter to run

splits an array into equal chunks
puts the remainder in the last chunk
returns a single chunk when size is larger than the array
size 1 wraps every item
returns [] for an empty array
returns [] when size is less than 1
does not mutate the input
esc