Created
October 8, 2020 03:59
-
-
Save afrijaldz/16bc1b3e0f08dbf15c8799a0984aaa19 to your computer and use it in GitHub Desktop.
create chunk of array with same size
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
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