Roger Almeida Leite Roger Almeida Leite - 2 months ago 21
Javascript Question

How to filter multiple values in a dc/crossfilter dimension?

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.


...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:

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,


Crossfilter requires a custom filter function for this. This is what dc.js does internally.

Applying to a dc.js chart

If you're using a dc chart you can just apply the filter via the chart's filter function, which unfortunately has different syntax and semantics:


Note the extra set of brackets. Weird right? I do not know how it evolved this way. Note, dc also 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 actually applies filters to crossfilter. Note that this just a slightly more complicated version of my second answer below.

Directly with crossfilter

If instead you want to apply a multivalue filter directly in crossfilter, probably it's best to use a function to generate the filter function, like so:

function multivalue_filter(values) {
    return function(v) {
        return values.indexOf(v) !== -1;