RedGiant
RedGiant

Reputation: 4748

Slicing an array into several chunks

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)

Upvotes: 1

Views: 79

Answers (1)

Barmar
Barmar

Reputation: 781096

The incorrect headings are because you have the arguments to the iteration function in the wrong order in the first .map() call. The first argument is the value, the second argument is the key. It should be:

chunks[i].map(function (v, key) {

The empty tables are because of a typo. This line:

 item_html += "</tr></tbody><table>";

should be:

 item_html += "</tr></tbody></table>";

You were missing the / in </table>.

The corrected loop is:

for (var i = 0; i < chunks.length; i++) {

    item_html += "<table><thead><tr>";

    chunks[i].map(function (v, key) {
        item_html += "<th>" + key + "</th>";
    });
    item_html += "</tr></thead><tbody><tr>";

    chunks[i].map(function (v) {
        item_html += "<td>" + v.number + "</td>";
    });

    item_html += "</tr></tbody></table>";

}

There was no point to the extra (i, ...) that you had around each call to .map(), so I removed it.

Updated fiddle

Upvotes: 2

Related Questions