0

I am trying to build an airport style terminal arrival/departure table view. Trying to make the rows viewable dynamic depending on viewable window. I have an array that could have any number of rows. Each row is an array itself. I am trying to break up the rows in the array into chunks depending on how much table rows the view can support.

So my question is I'm not sure how to break it up into chunks properly depending on dynamic sizes I want the chunks to be in. I've tried slice and splice but it only adds to the first element in the shortArrays then the rest of the elements are all empty.

INCOMING DATA:

array([array1], [array2], [array3], [array4], [array5], [array6], [array7], [array8], [array9], [array10], [array11], [array12], [array13]), [array14]), [array15]))

OUTGOING DATA:

array([[array1], [array2], [array3], [array4], [array5], [array6],  [array7], [array8], [array9], [array10]], [[array11], [array12], [array13], [array14], [array15]])  // 2 rows, row1: 10 arrays, row2: 5 arrays
var jsonData = JSON.parse(data); // data is value returned from ajax
var maxRowsPerTableView = 10; // Hardcoded as an example
var totalTablesToMake = 2; // Hardcoded as an example
var longArray = jsonData;
var shortArrays = [];
var tempCount, doorCount = 0; // Keeps track of which index

for(a = 0; a < totalTablesToMake; a++)
{
    temp = [];

    for(b = 0; b < maxRowsPerTableView; b++)
    {
        temp.push(longArray[b + doorCount]);
        tempCount = b;
    }

    doorCount += tempCount;
    shortArrays.push(temp);
}

RESULT:

shortArrays([10 elements],[10 elements]) // This isn't actual output, just a visual description so you can see what results I get.

This current code will output: shortArrays with 2 rows, each rows have 10 elements. So let's say there is only 15 elements in the jsonData. The second row in shortArrays will still have 10 elements, but the last 5 will be undefined.

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
khmer2040
  • 159
  • 1
  • 5
  • 16
  • 2
    please add some data and the wanted output. – Nina Scholz Apr 17 '17 at 15:31
  • add a break in the inner loop if(b+a*maxRowsPerTableView>=longArray.length) break mainforloop; – Jonas Wilms Apr 17 '17 at 15:49
  • `const toGroupsOf = (n, array) => Array.from({ length: Math.ceil(array.length / n) }, (v,i) => array.slice(i*n, (i+1)*n));` and then `var shortArrays = toGroupsOf(10, jsonData);` – Thomas Apr 17 '17 at 16:08

1 Answers1

1
longArray[b + doorCount] 

will return undefined if youre out of the arrays bounds. So you either fill in sth else ( an Array for Example)

longArray[b + doorCount]||[];

Or you stop the loop then:

mainloop:for(a = 0; a < totalTablesToMake; a++)
{
temp = [];

for(b = 0; b < maxRowsPerTableView; b++)
{
   if(b+a*maxRowsPerTableView>=longArray.length) break mainloop; 
    temp.push(longArray[b + doorCount]);
    tempCount = b;
}

doorCount += tempCount;
shortArrays.push(temp);
} 
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151