0

I'm starting learning crossfilter using data from my bank-account transactions list:

╔════════════════╦════════╗
║ Transact. date ║ Amount ║
╠════════════════╬════════╣
║ 2000-01-01     ║ +100 $ ║
║ 2000-01-02     ║  -25 $ ║
║ 2000-02-01     ║ -100 $ ║
║ 2000-03-01     ║  +50 $ ║
╚════════════════╩════════╝

I want to get total amounts by month and also partial account balance (i.e. the incremental sum of monthly total amounts). Here is the desired output based on the sample-data I just given:

╔═════════╦═════════════╦═══════════════╗
║ Month   ║ Tot. amount ║ Part. balance ║
╠═════════╬═════════════╬═══════════════╣
║ 2000-01 ║       +75 $ ║          +75$ ║
║ 2000-02 ║      -100 $ ║          -25$ ║
║ 2000-03 ║       +50 $ ║          +25$ ║
╚═════════╩═════════════╩═══════════════╝

I have no problem on getting the total amounts, but I can't understand how to calculate the partial sums for the monthly balance. Here is my code:

var ndx = crossfilter(data);
var month = ndx.dimension(function(d) { return d3.time.month(d.date); });
var amountByMonth = month.group().reduceSum(function(d) { return d.amount; });
var balanceByMonth = null; // TODO
4

1 回答 1

1

A simple but effective way would be to loop over your months and calculate the running total.

var months = Object.keys(amountByMonth).sort();
var runningTotal = 0;
for(var i = 0, l = months.length; i < l; i++) {
  var month = months[i];
  runningTotal += amountByMonth[month];
  balanceByMonth[month] = runningTotal;
}

Since the number of months will always be manageable (even for many years worth of data) this should be fine.

于 2013-08-02T21:50:55.490 回答