Skip to content

Instantly share code, notes, and snippets.

@afrijaldz
Created October 8, 2020 03:59
Show Gist options
  • Save afrijaldz/16bc1b3e0f08dbf15c8799a0984aaa19 to your computer and use it in GitHub Desktop.
Save afrijaldz/16bc1b3e0f08dbf15c8799a0984aaa19 to your computer and use it in GitHub Desktop.
create chunk of array with same size
const colors = ['red', 'blue', 'yellow', 'purple', 'green', 'grey', 'brown', 'white', 'black']
function chunkArray(myArray, chunk_size) {
let index = 0
let arrayLength = myArray.length
let tempArray = []
for (index = 0; index < arrayLength; index += chunk_size) {
let myChunk = myArray.slice(index, index + chunk_size)
tempArray.push(myChunk)
}
return tempArray
}
const chunkedArray = chunkArray(colors, 4)
console.log(chunkedArray) // [["red", "blue", "yellow", "purple"], ["green", "grey", "brown", "white"], ["black"]]
// inspired by https://ourcodeworld.com/articles/read/278/how-to-split-an-array-into-chunks-of-the-same-size-easily-in-javascript
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment