2
votes

Let me say that I have this data and dimension:

var data = [
      {"fruit": "apple", "amount": "12"},
      {"fruit": "orange", "amount": "6"},
      {"fruit": "grape", "amount": "11"},
      {"fruit": "melon", "amount": "26"},
      {"fruit": "lemon", "amount": "15"}
    ]

var ndx = crossfilter(data);
var fruitDimension = ndx.dimension(function (d) {
                            return d.fruit;
                        });

...and now, I want to filter just "apple","lemon" and "orange" just by using code. By now, I am trying to do something like.

fruitDimension.filter(["apple","lemon","orange"])

...but it does not work it all.

  • I know that the function # dimension.filterExact(value) works for one value.

    • If I apply # dimension.filter(value) passing a vector as parameter, it deals with it as # dimension.filterRange(range)

    • I could not find which filter works for different values.

references from: https://github.com/square/crossfilter/wiki/API-Reference

Someone has a hint about what I could be doing in order to filter different elements (that do not follow a range order) of a dimension?

Thanks in advance, Roger

1
Is pure js solution ok?Nenad Vracar
Hello Nenad, thanks for your fast return. I guess not my friend, because after this filter I am intending to make an dc.redrawAll() and have my charts updated according to this filter. However, if your pure js solution guarantees the crossfilter dimension set, yes, it would be ok. =)Roger Almeida Leite

1 Answers

9
votes

Crossfilter requires a custom filter function for this. dc.js supplies one.

Applying to a dc.js chart

If you're using a dc chart you should apply the filter via the chart's filter function, which has different syntax and semantics from the crossfilter dimension filter:

chart.filter([["apple","lemon","orange"]]);

Note the extra set of brackets. Weird right? I do not know how it evolved this way. Also, dc will toggle each value, so if you want to replace the filter, use replaceFilter instead of filter.

This is documented in the filterHandler function, which is where dc.js applies filters to crossfilter.

The chart doesn't know about changes directly to the crossfilter dimension: if you use the chart's .filter() then the chart will update the visual selection.

Directly with crossfilter

If instead you want to apply a multivalue filter directly to a crossfilter dimension, here is a function that generates a filter function for an array of values:

function multivalue_filter(values) {
    return function(v) {
        return values.indexOf(v) !== -1;
    };
}
fruitDimension.filterFunction(multivalue_filter(["apple","lemon","orange"]));