Search code examples
javascriptjsoncrossfilter

Using crossfilter to dynamically return results in JavaScript


I feel that the crossfilter library API explanation is written for someone above my skillset, but I also know that mastering it will solve my problem.

To make it simple, I will reference the API Page's example data for this question.

var payments = crossfilter([
  {date: "2011-11-14T16:17:54Z", quantity: 2, total: 190, tip: 100, type: "tab"},
  {date: "2011-11-14T16:20:19Z", quantity: 2, total: 190, tip: 100, type: "tab"},
  {date: "2011-11-14T16:28:54Z", quantity: 1, total: 300, tip: 200, type: "visa"},
  {date: "2011-11-14T16:30:43Z", quantity: 2, total: 90, tip: 0, type: "tab"},
  {date: "2011-11-14T16:48:46Z", quantity: 2, total: 90, tip: 0, type: "tab"},
  {date: "2011-11-14T16:53:41Z", quantity: 2, total: 90, tip: 0, type: "tab"},
  {date: "2011-11-14T16:54:06Z", quantity: 1, total: 100, tip: 0, type: "cash"},
  {date: "2011-11-14T16:58:03Z", quantity: 2, total: 90, tip: 0, type: "tab"},
  {date: "2011-11-14T17:07:21Z", quantity: 2, total: 90, tip: 0, type: "tab"},
  {date: "2011-11-14T17:22:59Z", quantity: 2, total: 90, tip: 0, type: "tab"},
  {date: "2011-11-14T17:25:45Z", quantity: 2, total: 200, tip: 0, type: "cash"},
  {date: "2011-11-14T17:29:52Z", quantity: 1, total: 200, tip: 100, type: "visa"}
]);

I am able to return records that match a specific key (quantity, total, etc.), but I do not understand how to return results that match a combination of key/value pairs. For instance, how would I return the result set that matched results with a quantity more than 1, a total equal 90, a tip equal 0 and a type of tab? This is where I'm completely lost.


Solution

  • You could create a dimension for each attribute and then call each dimension's filter method with the corresponding filter criteria you indicated, like so.

    var payments_by_quantity = payments.dimension(function(d){return d.quantity}),
        payments_by_total = payments.dimension(function(d){return d.total}),
        payments_by_tip = payments.dimension(function(d){return d.tip}),
        payments_by_type = payments.dimension(function(d){return d.type});
    
    payments_by_quantity.filter([1, Infinity]);
    payments_by_total.filter(90);
    payments_by_tip.filter(0);
    payments_by_type.filter("tab");
    
    payments_by_type.top(Infinity)
    

    The effects are cumulative, so that last line there is actually the result of all values respecting all filters from all dimensions.