Faisal
Faisal

Reputation: 31

Sum of multiple column values for each row in d3.js

I am using a .csv file which requires to find sum of the multiple column values against each key in each row. The example is as below-

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

So I need to find the sum of "value1 + value2 + value3 + value4" against each key in a dynamic way rather mentioning d.value1 + d.value2 + d.value3 + d.value4.

Thanks...

Upvotes: 3

Views: 2897

Answers (2)

Cetin Basoz
Cetin Basoz

Reputation: 23797

This is very late, but anyway someone might need it. d3 has a sum method. ie:

var data = `key,value1,value2,value3,value4
mike,1,3,5,7
mila,2,4,6,8
minda,9,11,13,15`;
var summedData = d3.csvParse(data, function (d, i, columns) 
          { d3.autoType(d);
            d.total = d3.sum(columns, c => d[c]);
            return d;
          });
      
console.log(summedData);

Attaches row "total" to each row.

Upvotes: 0

Mark
Mark

Reputation: 108512

Are you making an AJAX request for the CSV? If you want to process it in there:

d3.csv("data.csv")
  .row(function(d) {
    return {
      key: d.key,
      mySum: ((+d.value1) + (+d.value2) + (+d.value3) + (+d.value4))
    };
  })
  .get(function(error, rows) {
    console.log(rows);
  });

Example here.

Edited for Comments

If you don't know the number of columns, do something like this:

d3.csv("data.csv")
  .row(function(d) { 
    var mySum = 0;
    for (var o in d) { // iterate all the properties of d
      if (o === "key") continue; // if it's our key field skip it
      else mySum += +d[o]; // everyone else into the sum
    }
    return {
      key: d.key, 
      mySum: mySum
    };
  })
  .get(function(error, rows) { 
    console.log(rows); 
  });

Updated example.

Upvotes: 1

Related Questions