Skip to content

Instantly share code, notes, and snippets.

@l-portet
Created January 6, 2021 10:34
Show Gist options
  • Save l-portet/3e6db6c9480273bcbd9a6b5daf916715 to your computer and use it in GitHub Desktop.
Save l-portet/3e6db6c9480273bcbd9a6b5daf916715 to your computer and use it in GitHub Desktop.
Split & stack an array into chunks
// Split & stack an array into chunks
// Ex: arrayChunk([1, 2, 3, 4, 5, 6, 8], 3) => [[1, 2, 3], [4, 5, 6], [7, 8]]
function arrayChunk (arr = [], len = 2, stackRest = false) {
const chunks = [];
const n = arr.length;
let i = 0;
while (i < n) {
const chunk = arr.slice(i, i += len);
if (stackRest && chunk.length !== len) {
chunks[chunks.length - 1].push(...chunk);
} else {
chunks.push(chunk);
}
}
return chunks;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment