Skip to content

Instantly share code, notes, and snippets.

@nluo
Created September 2, 2018 08:15
Show Gist options
  • Save nluo/7c13fff648c9f96447281e48ab9d094a to your computer and use it in GitHub Desktop.
Save nluo/7c13fff648c9f96447281e48ab9d094a to your computer and use it in GitHub Desktop.
Array Chuck question
// --- Directions
// Given an array and chunk size, divide the array into many subarrays
// where each subarray is of length size
// --- Examples
// 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, 4, 5, 6, 7, 8], 3) --> [[ 1, 2, 3], [4, 5, 6], [7, 8]]
// chunk([1, 2, 3, 4, 5], 4) --> [[ 1, 2, 3, 4], [5]]
// chunk([1, 2, 3, 4, 5], 10) --> [[ 1, 2, 3, 4, 5]]
function chunk(array, size) {
if (array.length === 0) {
return []
}
const left = array.slice(0, size)
const right = array.slice(size)
return [left].concat(left, chunk(right, size))
}
module.exports = chunk;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment