Let's say that I have an Javascript array looking as following:
["Element 1","Element 2","Element 3",...]; // with close to a hundred elements.
What approach would be appropriate to chunk (split) the array into many smaller arrays with, lets say, 10 elements at its most?
There have been many answers but this is what I use:
First, check for a remainder when dividing the index by the chunk size.
If there is a remainder then just return the accumulator array.
If there is no remainder then the index is divisible by the chunk size, so take a slice from the original array (starting at the current index) and add it to the accumulator array.
So, the returned accumulator array for each iteration of reduce looks something like this:
Here is a non-mutating solution using only recursion and slice().
Then simply use it like
splitToChunks([1, 2, 3, 4, 5], 3)
to get[[1, 2, 3], [4, 5]]
.Here is a fiddle for you to try out: https://jsfiddle.net/6wtrbx6k/2/
This should be straightforward answer without many mathematical complications.
Hi try this -
Old question: New answer! I actually was working with an answer from this question and had a friend improve on it! So here it is:
Nowadays you can use lodash' chunk function to split the array into smaller arrays https://lodash.com/docs#chunk No need to fiddle with the loops anymore!