For loop through array and group every x number of items

If you for loop through an array of items, what’s the best way to group the output into sections of a set number. For example, group items into a divs, with 12 items per div?


Hi Jon,

You could use the Array.slice() method within a loop, to grab a fixed size chunk to work with:

var j = items.length,
	chunk = 12,

for (var i=0; i < j; i += chunk) {
    subset = items.slice(i, i+chunk);
    // output DIV with 12 items
1 Like

The best way is to NOT use a loop to process an array in JavaScript. There are quite a few methods that will process all the entries in the array with no loop needed.

The following will wrap div tags around every 12 array entries in the items array outputting them to the str string (with a space immediately following each individual array entry.

str = '<div>';
items.forEach(function(a,b,c) {str += a+' '; if(b%12===0 && b<c) str+= '</div><div>'});
str += '</div>';

Thanks fretburner, I’ll give it a go.

Also, thanks felgall, but forEach doesn’t work below IE9 and I need to support below that. Would jQuerys each work in the same way?

Thanks again guys.

I had to go through a list of products and group every 4 of them to make “rows”. Since we were using jQuery I wrote it in that. I used map, which is about a hundred million gazillion times slower than for loops, but they were way easier to read since there were also lots of for loops anyway.

So one shop had a “rowlength” of 4 items (like fretburner’s “chunk”).

I have zero idea why my last bracket isn’t within the code set. The three backticks didn’t work and trying to highlight and hit the </> thing didn’t work either. Frustrating. I should be able to wrap something around code so the software can’t mess it up.

function generateRows(list, rowLength) {                                        
    var rows = [],                                                              
        currentRow = [];                                                        
                                                                       , li) {                                                  
        if (i % rowLength === 0 && i !== 0) {                                   
            currentRow = [];                                                    
    return rows;                                                                


This was a function other functions called to make AoAs.

Arg, Discourse won’t let me select and copy some text from jonpenny either! I’m writing it by hand, arg!!!
Also putting my focus in this box always jumps it back up to the top of the post, instead of where I try to set it. Software should never be allowed to try to outsmart the users.

So far as I know, jQuery’s $each is, internally, a bunch of for loops, though maybe they have forEach in there for the modern browsers, but for IE they needed regular for loops anyway. So as far as the browser’s concerned, it’s doing the same work as a bunch of for loops either way.

So add the following to implement forEach in antiquated browsers that don’t support it - while allowing those that do to continue using the built in version

if ( !Array.prototype.forEach ) {
  Array.prototype.forEach = function forEach( callback, thisArg ) {
    var T, k, O, len;
    if ( this == null ) {
      throw new TypeError( "this is null or not defined" );
    O = Object(this);
    len = O.length >>> 0;
    if ({} !== "[object Function]" ) {
      throw new TypeError( callback + " is not a function" );
    if ( thisArg ) {
      T = thisArg;
    k = 0;
    while( k < len ) {
      if (, k) ) { T, O[ k ], k, O );
1 Like

oooh shifty