singh
singh

Reputation: 79

How can we Sum the data of .csv file columnwise using d3.js

Given this .csv file:

date,jan,feb,march
1-1-2011,1,2,3  
1-2-2011,2,3,4  
1-3-2011,1,4,5

and I want an array that contains value like: [4,9,12].

Upvotes: 0

Views: 2399

Answers (2)

Gerardo Furtado
Gerardo Furtado

Reputation: 102174

Even though thatOneGuy's answer is perfect, this is way shorter:

d3.csv("yourFile.csv", function(data){

    var totalSum = [d3.sum(data.map(function(d){ return d.jan})),
       d3.sum(data.map(function(d){ return d.feb})),
       d3.sum(data.map(function(d){ return d.march}))];

    console.log(totalSum);//[4, 9, 12]

});

Upvotes: 3

thatOneGuy
thatOneGuy

Reputation: 10612

Something like this will work :

d3.csv('linktocsvfilehere.csv',function(data){

var sumArray = [];
var janArray= [], febArray= [], marchArray = [];

data.forEach(function(d){
   janArray.push(d.jan); //push all jan values into jan array
   febArray.push(d.feb); //push all feb values into feb array
   marchArray.push(d.march); //push all march values into march array
});

var janSum = getSumOfArray(janArray); //get sum of jan array
var febSum = getSumOfArray(febArray);
var marchSum = getSumOfArray(marchArray);

sumArray.push(janSum,febSum,marchSum);

console.log(sumArray); //here is your array you want

function getSumOfArray(array){

   var thisSum = 0;

   for(var i = 0; i<array.length; i++){
      thisSum += array[i];
   }
   return thisSum;
}
})

Upvotes: 1

Related Questions