user2571510 user2571510 - 1 month ago 8
jQuery Question

Create list / array of table values

I have a table with 6 fixed columns that looks like the below and variable content that is created dynamically. Within each column a value can only appear once but may not appear in all columns.

Is there a way I can get a list / array with all the values from the columns Cat and the volumes from columns Vol like the example variables below?

My table:

<table id="myTable">
<thead>
<tr>
<th class="myHeader">Cat 1</th>
<th>Vol 1</th>
<th class="myHeader">Cat 2</th>
<th>Vol 2</th>
<th class="myHeader">Cat 3</th>
<th>Vol 3</th>
//...
</tr>
</thead>
<tbody>
<tr>
<td>item1</td><td>8</td><td>item2</td><td>7</td><td>item3</td><td>9</td>
</tr>
<tr>
<td>item3</td><td>5</td><td>item2</td><td>7</td><td>item1</td><td>4</td>
</tr>
<tr>
<td>item2</td><td>1</td><td>item1</td><td>5</td><td>item3</td><td>3</td>
</tr>
//...
</tbody>
</table>


Required output:

var item1 = [8, 4, 5]
var item2 = [7, 7, 1]
var item3 = [9, 5, 3]

Answer

Try this:

$(document).ready(function() {

    var items ={
        item1: [],
        item2: [],
        item3: []
    };
    $('#myTable > tbody > tr').each(function() {
        var cols = $(this).find('td');
        for (var col = 0; col < cols.length; col += 2) {
            items[$(cols[col]).text()].push(+$(cols[col + 1]).text());
        }
    });
    console.log(items);
});

Working example: http://jsfiddle.net/QLyKk/ (I left a item empty to show that in this case a 0 is put in the array)

Comments