Split array into chunks

Industrial picture Industrial · Dec 13, 2011 · Viewed 603.2k times · Source

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?

Answer

Blazemonger picture Blazemonger · Dec 13, 2011

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.

var i,j,temparray,chunk = 10;
for (i=0,j=array.length; i<j; i+=chunk) {
    temparray = array.slice(i,i+chunk);
    // do whatever
}