Created
January 6, 2021 10:34
-
-
Save l-portet/3e6db6c9480273bcbd9a6b5daf916715 to your computer and use it in GitHub Desktop.
Split & stack an array into chunks
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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