Sometimes, we want to split a JavaScript array into N arrays.
In this article we’ll look at how to split a JavaScript array into N arrays.
How to split a JavaScript array into N arrays?
To split a JavaScript array into N arrays, we can use a for loop.
For instance, we write
const splitToChunks = (array, parts) => {
const arrayCopy = [...array];
let result = [];
for (let i = parts; i > 0; i--) {
result.push(arrayCopy.splice(0, Math.ceil(arrayCopy.length / i)));
}
return result;
};
to define the splitToChunks
function that takes the array
to split and the number of parts
to split array
into.
In it, we make a copy of the original array and assign it to arrayCopy
so the original array
is unaffected.
Then we use a for loop to loop from parts
to 1.
And in the loop, we call arrayCopy.splice
to return the slice between index 0 and Math.ceil(arrayCopy.length / i)
and push returned array slice into the result
array.
Conclusion
To split a JavaScript array into N arrays, we can use a for loop.