且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Crossfilter中的自定义计算的聚合字段

更新时间:2023-02-12 16:11:31

希望这对您仍然有用。

您可以通过定义reduceAdd来实现,针对您的特定用例的reduceRemove和reduceInitial函数,然后将它们传递给reduce。

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

代码:

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);

Crossfilter添加记录时,它使用reduceAdd重新计算值。当Crossfilter删除筛选出的记录时,它将使用reduceRemove更新值。它需要一个由reduceInitial提供的初始值(请注意,这是一个函数)。请参阅文档 https://github.com/square/crossfilter/wiki的此永久链接/ API-Reference#group_reduce

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.

我使用了上面给出的输入,因此得到的是json:

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.