darkpool darkpool - 1 year ago 52
HTML Question

Sum table values based on grouping

I have the following table:

<td class="cat1">cat1</td>
<td class="value">123</td>
<td class="cat2">cat2</td>
<td class="value">356</td>
<td class="cat1">cat1</td>
<td class="value">486</td>

I need a way to add/sum all values grouped by category, ie: add/sum all values in
, then add/sum all values in
. For each group I will do something with the total.

So I was hoping for something like:

for each unique category:
sum values in category
do something with this category total

the total would be 123 + 486.
would just be 356. And so on if there were more categories.

I would prefer a purely javascript solution, but JQuery will do if that's not possible.

Answer Source

Here's a simple approach using only javascript

//grab data
var allTR = document.getElementsByTagName('TR');

var result = {};

//cycle table rows
for(var i=0;i<allTR.length;i+2){
    //read class and value object data
    var class = allTR[i].getAttribute('class');
    var value = allTR[i+1].innerText;

    //check if exists and add, or just add
       result[class] += parseInt(value);
       result[class] = parseInt(value);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download