0

In our dc.js powered d3.js chart.

Trying to concatenate a few boolean expressions inside crossfilter's's filter function by using code appending approach.

var field1 = true,
  field2 = "XYZ",
  field3 = "ABC",
  field4 = 1
var filteredData = jsonObject.filter(function(d) {

  //condition 1
  if (field1 != true && field2 != "GHI") {
    var _dataFilter = d.FieldOne >= field1 &&
      d.FieldTwo <= field2 &&
      d.FieldThree == field3 &&
      d.FieldFour == field4
  }

  return _dataFilter;
});

console.log("FieldOne " + field1 + " FieldTwo " + field2 + " FieldThree " + field3 + " FieldFour " + field4);

var sourceDataForChart = crossfilter(filteredData);

I'm finding that _dataFilter is coming as nothing on console. By this, I mean literally nothing. No undefined, no object, no value, no function is returned. sourceDataForChart is the data being used by the chart

I need to implement it for a grouping requirement, there will be a lot of conditions. How do I do it?

Zameer Ansari
  • 28,977
  • 24
  • 140
  • 219
  • What does `jsonObject` look like? This doesn't really look like a Crossfilter question, as it appears you are trying and failing to filter the data before it is put into the Crossfilter. So this is a pure Javascript issue? – Ethan Jewett Aug 26 '16 at 20:50

1 Answers1

0

I agree with Ethan that this is JavaScript question.

Usually you don't want functions that will return undefined in some circumstances, and a value in other circumstances. Your variable _dataFilter will only get initialized if the conditions are true - and right now the condition is false because field1is true.

In fact, it's only because JavaScript hoists all variables to the function scope that the variable even exists when it's returned. So maybe this is why the debugger is reporting no value.

A better organization for the code would be

var filteredData = jsonObject.filter(function(d) {
  var _dataFilter = false;
  // condition 1
  if (field1 != true && field2 != "GHI") {
      _dataFilter = d.FieldOne >= field1 &&
        d.FieldTwo <= field2 &&
        d.FieldThree == field3 &&
        d.FieldFour == field4
  }
  else if (/* more conditions */ ) {
       _dataFilter = /* ... */
  }
  return _dataFilter;
});
Gordon
  • 19,811
  • 4
  • 36
  • 74