Custom calculated aggregated field in Crossfilter Custom calculated aggregated field in Crossfilter json json

Custom calculated aggregated field in Crossfilter


Hope this is still useful to you.

You can do this by defining reduceAdd, reduceRemove and reduceInitial functions for your specific use case and then passing them to reduce.

Code:

var cf   = crossfilter(data),    year = cf.dimension(function(d) { return d.year; });var reduceAdd = function(p, v) {    p.tons_available += v.tons_available;    p.tons_sold      += v.tons_sold;    p.str            = p.tons_sold/p.tons_available;    return p;}var reduceRemove = function(p, v) {    p.tons_available -= v.tons_available;    p.tons_sold      -= v.tons_sold;    p.str            = p.tons_sold/p.tons_available;    return p;}var reduceInitial = function() {    return {        tons_available : 0,        tons_sold      : 0,        str            : 0    }}var json = year.group().reduce(reduceAdd,reduceRemove,reduceInitial).orderNatural().top(Infinity);console.log(json);

When Crossfilter adds records it uses reduceAdd to recalculate values. When Crossfilter removes filters out records it uses reduceRemove to update values. It needs an initial value which is supplied by reduceInitial (note that it's a function). See this permalink from the docs https://github.com/square/crossfilter/wiki/API-Reference#group_reduce.

I used the input that you gave above and this is the json that I got as a result:

[{key: "1988", value: {    str: 0.37404580152671757,    tons_available: 131,    tons_sold: 49}, {key: "1987", value: {    str: 0.6901408450704225,    tons_available: 71,    tons_sold: 49}]

It's not exactly the output you asked for, but it's pretty close.