frequent frequent - 1 year ago 77
Javascript Question

How to split xxxx table rows into arrays of 100 each using jquery and account for rounding?

I'm trying to paginate a table using jquery.

I want to split xxxx number of rows into arrays of 100 rows each, which I can then run through to populate the subpages I'm creating.

currently I'm trying this:

var rowsPerPageS = 100,
maxRows = table.find( "tbody tr, TBODY TR" ).length,
splitRows = [];

// split table array into array of 100
for( i = 0; i < Math.round(maxRows/rowsPerPageS); i++){
splitRows.push( $( table ).find( "tbody tr, TBODY TR" ).slice( rowsPerPage*i,rowsPerPageS*(i+1) ) )

The above seems to work well for 100,200,300,400 etc rows, which will give me 1,2,3,4 objects in my array. But if I have 333 rows for example, 333/100 = 3.33 = 3 objects and I'm "dropping" the last 33 rows.


how can I account for number of "uneven" number of rows? If I add +1 to the number of loops I will be getting an empty object if rows are 100,200,300 or <99, so this is not possible.

Can someone help me out?

Answer Source

"I want to split xxxx number of rows into arrays of 100 rows each"

Give this a shot...

var rowsPerPageS = 100,
    splitRows = [],
    rows = $( table ).find( "tbody tr" ).toArray();

for( i = 0; i < rows.length; i += rowsPerPageS ){
    splitRows.push( rows.slice(i, i + rowsPerPageS ) );

You can get rid of .toArray() if you actually wanted jQuery objects.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download