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?
Modified from an answer by dbaseman: https://stackoverflow.com/a/10456344/711085
Demo:
minor addendum:
I should point out that the above is a not-that-elegant (in my mind) workaround to use
Array.map
. It basically does the following, where ~ is concatenation:It has the same asymptotic running time as the method below, but perhaps a worse constant factor due to building empty lists. One could rewrite this as follows (mostly the same as Blazemonger's method, which is why I did not originally submit this answer):
More efficient method:
My preferred way nowadays is the above, or one of the following:
Demo:
Or if you don't want an Array.range function, it's actually just a one-liner (excluding the fluff):
or
Created a npm package for this https://www.npmjs.com/package/array.chunk
I think this a nice recursive solution with ES6 syntax:
I'd prefer to use splice method:
The array.slice method can extract a slice from the beginning, middle, or end of an array for whatever purposes you require, without changing the original array.