split an array into smaller arrays in Javascript
Code snippet on how to split an array into smaller arrays in Javascript
const splitArray = (arr, size) => {
const splittedArrays = [];
let index = 0;
while (index < arr.length) {
splittedArrays.push(arr.slice(index, index + size));
index += size;
}
return splittedArrays;
}
This code takes an array, arr
, and a number, size
. It then creates an empty array, splittedArrays
, and a variable index
that is initially set to 0. Next, there is a while loop that will continue to run until the index
is greater than the arr.length
. The loop pushes a new array with elements from the arr
starting at the index
position and ending at index
plus size
. Afterwards, the index
is incremented by size
. The loop will repeat until the index
is greater than the arr.length
. At this point, the splittedArrays
will have been populated and the code will return it.