HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

Dividing an array

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
arraydividingstackoverflow

Problem

I need to divide an array in blocks of 6 items max, however I can't find a better way to store the last block.

This is my current code and it works. Is there a way to avoid using the if after the .each ?

var tabsData = [], tabCtr = 1, lpcCtr = 1;
    $.each(PAGE_DATA.tableData, function(i, item) {
        tabsData.push(item);
        if(lpcCtr==6){
            // show block of 6 items
            tabsData = [];
            tabCtr++;
            lpcCtr = 0;
        }
        lpcCtr++;
    });
    if(tabsData.length > 0){
        // show last block
    }

Solution

It's better to use slice function. It will also correctly process the last block

var size = PAGE_DATA.tableData.length;
for (var i = 0; i < size; i += 6){
     var t = PAGE_DATA.tableData.slice(i, i + 6);
     //show block of 6 items (or smaller in case of last block)
}

Code Snippets

var size = PAGE_DATA.tableData.length;
for (var i = 0; i < size; i += 6){
     var t = PAGE_DATA.tableData.slice(i, i + 6);
     //show block of 6 items (or smaller in case of last block)
}

Context

StackExchange Code Review Q#19266, answer score: 3

Revisions (0)

No revisions yet.