samedi 14 février 2015

Calculating an average from a javascript array


I'm trying to get a monthly average figure from some spending data. I'm using d3.js to import and roll up the data from a csv, but I can't seem to filter out just the values from the resulting array before I go on to calculate the average spend.


I'm new to Javascript, and none of it feels at all intuitive.



// get filtered data (df)
d3.csv("/data/cic_data.csv", function (csv) {

// roll up and group data
var data = d3.nest()
.key(function(d) { return d.date; })
.rollup(function(d) {
return d3.sum(d, function(g) {return g.spend; });
}).entries(csv);

var valueData = data.filter(function(d) {
return d.values;
})

var sum = 0;
for( var i = 0; i < data.length; i++ ){
sum += parseInt( data[i], 10 ); //don't forget to add the base
}

var avg = sum/data.length;

console.log(avg)


Here's a sample of my csv:



entity,level1,level2,supplier,type,date,spend,year,sin
BARKING DAGENHAM LONDON BOROUGH COUNCIL,Local Government,LONDON,GREEN SHOES ARTS COMMUNITY INTEREST COMPANY,LARGE,2014-07-01,4001.50,2014,12
BARKING DAGENHAM LONDON BOROUGH COUNCIL,Local Government,LONDON,GREENSPACE INFORMATION FOR GREATER LONDON CIC,OTHER,2014-07-01,2400.00,2014,12
BARKING DAGENHAM LONDON BOROUGH COUNCIL,Local Government,LONDON,GREEN SHOES ARTS COMMUNITY INTEREST COMPANY,LARGE,2014-06-01,8995.00,2014,12
BARKING DAGENHAM LONDON BOROUGH COUNCIL,Local Government,LONDON,GREEN SHOES ARTS COMMUNITY INTEREST COMPANY,LARGE,2014-05-01,640.00,2014,12
BARKING DAGENHAM LONDON BOROUGH COUNCIL,Local Government,LONDON,PUBLIC HEALTH ACTION SUPPORT TEAM CIC,SMALL,2014-05-01,6480.00,2014,12
BARKING DAGENHAM LONDON BOROUGH COUNCIL,Local Government,LONDON,GREEN SHOES ARTS COMMUNITY INTEREST COMPANY,LARGE,2014-04-01,7286.00,2014,12
BARKING DAGENHAM LONDON BOROUGH COUNCIL,Local Government,LONDON,GREEN SHOES ARTS COMMUNITY INTEREST COMPANY,LARGE,2014-03-01,15659.50,2014,12
BARKING DAGENHAM LONDON BOROUGH COUNCIL,Local Government,LONDON,THE SMALL BUSINESS CONSULTANCY LEICESTER CIC,OTHER,2014-03-01,6000.00,2014,12
BARKING DAGENHAM LONDON BOROUGH COUNCIL,Local Government,LONDON,GREEN SHOES ARTS COMMUNITY INTEREST COMPANY,LARGE,2014-02-01,4001.50,2014,12




Aucun commentaire:

Enregistrer un commentaire