darkpool darkpool - 3 months ago 8
HTML Question

Sum table values based on grouping

I have the following table:

<table>
<tr>
<th>Category</th>
<th>Value</th>
</tr>
<tr>
<td class="cat1">cat1</td>
<td class="value">123</td>
</tr>
<tr>
<td class="cat2">cat2</td>
<td class="value">356</td>
</tr>
<tr>
<td class="cat1">cat1</td>
<td class="value">486</td>
</tr>
</table>


I need a way to add/sum all values grouped by category, ie: add/sum all values in
cat1
, then add/sum all values in
cat2
. 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


For
cat1
the total would be 123 + 486.
Cat2
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

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
    if(result[class])
       result[class] += parseInt(value);
    else
       result[class] = parseInt(value);
}
Comments