Please take a look at this fiddle.
How can I slice an array into several small arrays
var data =
[ { number: '1' },
{ number: '2' },
{ number: '3' },
{ number: '4' },
{ number: '5' },
{ number: '6' },
{ number: '7' },
{ number: '8' },
{ number: '9' },
{ number: '10'}
];
and build a table for each of them? Example:
<table>
<thead>
<tr>
<th>Number</th><th>Number</th><th>Number</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td><td>2</td><td>3</td>
</tr>
</tbody>
</table>
<table>
<thead>
<tr>
<th>Number</th><th>Number</th><th>Number</th>
</tr>
</thead>
<tbody>
<tr>
<td>4</td><td>5</td><td>6</td>
</tr>
</tbody>
</table>
........
The following code isn't working. The output is kind of a mess. As you can see in the fiddle, I can't access the key(number), and there are empty <table></table> tags in between the tables. Can anyone show me how to slice the array properly.
Code:
var data = [ { number: '1' },
{ number: '2' },
{ number: '3' },
{ number: '4' },
{ number: '5' },
{ number: '6' },
{ number: '7' },
{ number: '8' },
{ number: '9' },
{ number: '10'}
];
var chunks = [];
var item_html ="";
for (var i=0; i<data.length; ) {
chunks.push(data.slice(i, i+=3));
}
for (var i=0; i<chunks.length; i++) {
item_html += "<table><thead><tr>";
(i, chunks[i].map(function(key,v){
item_html += "<th>"+key+"</th>";
}));
item_html += "</tr></thead><tbody><tr>";
(i, chunks[i].map(function(v){
item_html += "<td>"+v.number+"</td>";
}));
item_html += "</tr></tbody><table>";
}
$('#area').append(item_html)