Skip to content

Instantly share code, notes, and snippets.

@Luke-Rogerson
Created December 13, 2018 08:25
Show Gist options
  • Save Luke-Rogerson/14229cd6ea22c42b235d5605140b618f to your computer and use it in GitHub Desktop.
Save Luke-Rogerson/14229cd6ea22c42b235d5605140b618f to your computer and use it in GitHub Desktop.
Given an array and chunk size, divide the array into many subarrays where each subarray is of length size
// --- 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) {
const chunks = [];
let i = 0;
while (i < array.length) {
chunks.push(array.slice(i, i+=size))
}
return chunks;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment