-2

I have the following table :

a   b    c   d
--------------  
5   2   25  25  
2   48  20  20  
5   1   22  22  
3   4   31  31  
3   3   33  33  
3   6   43  43  
3   8   45  45  
3   5   42  42  
3   11  37  37  
3   7   40  40  
3   10  36  36  
1   35  40  40  
3   22  38  38  
3   23  35  35  
1   31  34  34  

I need to calculate sum of each column based on column A group i.e., group by A, results in the output:

a  b   c   d
------------    
1 20  30  15    
2 30  20  24    
3 10  30  16

Any one help me out

Zze
  • 18,229
  • 13
  • 85
  • 118
sabari
  • 31
  • 4
  • not very clear. please add what you have tried – guradio Sep 06 '16 at 09:32
  • You can combine these two.. First http://stackoverflow.com/questions/12290927/how-to-convert-html-table-to-javascript-object-with-jquery and then http://stackoverflow.com/questions/14427659/jquery-array-group-by.. In my opinion, i dont know what you need but this is server side issue which can be done easily in server side – mr. Sep 06 '16 at 10:00

2 Answers2

0

You can use var table = $('#example-table').tableToJSON(); to convert your data into json. Then with the help of generated json and for loop you can achieve your objective.

Click here GitHub Link for tableToJSON()

Abhijeet
  • 4,069
  • 1
  • 22
  • 38
  • Hi, I read the json file and made table. I am asking from the table i need to calculate sum of each column based on first column group i.e., in mysql we have group by column a. similar to that i am asking – sabari Sep 06 '16 at 09:50
  • Can you share json with me I'll come up with solution – Abhijeet Sep 06 '16 at 10:18
0

This code should be help you to calculate group by sum by first column

$(document).ready(function(){
  var group_sum={};
  $("#mytable tbody tr").each(function(){
    element=$(this).find('td:first').text();
    others=$.map($(this).find('td').not(':first'),function(ele,i){
      return parseFloat($(ele).text());
    });
    if(group_sum[element]==undefined)
    {
    group_sum[element]=others;
    }
    else
    {
      for(i in others)
      {
         group_sum[element][i]+=others[i];
      }
    }
    
  })
  console.log(group_sum);

})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<table id="mytable">
<thead>
 <tr>
  <th>A</th>
  <th>B</th>
  <th>C</th>
  <th>D</th>
 </tr>
</thead>
<tbody>
 <tr>
  <td>1</td>
  <td>11</td>
  <td>12</td>
  <td>13</td>
 </tr>
 <tr>
  <td>1</td>
  <td>10</td>
  <td>10</td>
  <td>10</td>
 </tr>
 <tr>
  <td>2</td>
  <td>10</td>
  <td>10</td>
  <td>10</td>
 </tr>
 <tr>
  <td>3</td>
  <td>10</td>
  <td>10</td>
  <td>10</td>
 </tr>
 <tr>
  <td>3</td>
  <td>10</td>
  <td>10</td>
  <td>10</td>
 </tr>

 <tr>
  <td>3</td>
  <td>10</td>
  <td>10</td>
  <td>10</td>
 </tr>
</tbody>
</table>
Haresh Vidja
  • 8,340
  • 3
  • 25
  • 42