Faisal
Faisal

Reputation: 31

Get sum total for each column in d3.js

I am looking forward to get the sum total of each column using d3.js in a dynamic way. Please find the example-

key  | value1 | value2 | value3 | value4 
-----+--------+--------+--------+--------
mike | 1      | 3      | 5      | 7      
-----+--------+--------+--------+--------
mila | 2      | 4      | 6      | 8
-----+--------+--------+--------+--------
minda| 9      | 11     | 13     | 15

Here, sum total for value1 is 12, value2 is 18. I need the sum for each of the column in a dynamic way.

Upvotes: 0

Views: 2895

Answers (1)

Ben Lyall
Ben Lyall

Reputation: 1976

I don't know how you're loading your data, but here's one way that you could do it.

var data = [
  { key: "mike",  value1: 1, value2: 3, value3: 5, value4: 7}, 
  { key: "mila",  value1: 2, value2: 4, value3: 6, value4: 8}, 
  { key: "minda", value1: 3, value2: 5, value3: 7, value4: 9}, 
  { key: "mandy", value1: 4, value2: 6, value3: 9, value4: 10}
];

var cols = d3.keys(data[0]),
    table = d3.select("#vis").append("table"),
    totals = {};

data.forEach(function(d) {
    cols.forEach(function(k) {
        if (k !== "key") {
            if (k in totals) {
                totals[k] += d[k];
            } else {
                totals[k] = d[k];
            }
        }
    });
});

totals['key'] = 'totals';

data.push(totals);

table.append("thead").append("tr").selectAll("th")
     .data(cols)
   .enter().append("th")
     .html(function(d) {
         return d;
      });

var rows = table.append("tbody").selectAll("tr")
                .data(data)
              .enter().append("tr")
                .html(function(d) {
                    html = "";
                    cols.forEach(function(k) {
                        html += "<td>" + d[k] + "</td>";
                    });

                    return html;
                });
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<div id="vis"></div>

It's pretty simple really, get the column names from your data (stored in cols) and for each row in your data, loop over those column names, adding the values in that column together and storing them in a new variable (totals in this example).

To display it, I'm just creating a table with the totals appended to the data so it creates a new row with the totals in it.

Upvotes: 1

Related Questions