javascriptarraysd3.jscheckbox

Iterating through an array inside a conditional && statement in javaScript?


I have an array:

console.log(tenantArray)
(8) ["WeWork", "Regus", "Spaces", "Knotel", "RocketSpace", "HQ Global Workspaces", "Other", "Select All"]

I also have a large data object, which I want to filter using d3, using a checkbox. The filter will be based on two conditions, the "Agency_Bro" property, and whether or not the "Tenant" property matches any of the strings in the tenantArray listed above. In this sense, the "tenantArray" array above is just a dummy used for string matching purposes. Both conditions have to be true for filter.

The filter works fine if it just reads:

d3.selectAll("#JLLCheckbox").on("change", function() {

            var type = "JLL"            
            display = this.checked ? "inline" : "none";
            d3.selectAll(".features")
            .filter(function(d) { 
                return d.properties.Agency_Bro === type             
            })
            .attr("display", display);
});

However, when I try to add in both conditional statements, the checkbox stops working (no data filtered) yet no error message occurs.

d3.selectAll("#JLLCheckbox").on("change", function() {

    var type = "JLL"            
    display = this.checked ? "inline" : "none";

    d3.selectAll(".features")
        .filter(function(d) { 
            return d.properties.Agency_Bro === type &&
                    tenantArray.forEach(function(entry) {
                    if (d.properties.Tenant === entry){
                        return d.properties.Tenant
                    }
                    });         
        })
});

Two questions: any reason the above logic is failing? And, is there a more efficient way to do this, without going through the trouble of the array?


Solution

  • You'd better replace forEach with some method to receive a true/false value:

    d3.selectAll("#JLLCheckbox").on("change", function() {
    
      var type = "JLL"
      display = this.checked ? "inline" : "none";
    
      d3.selectAll(".features")
        .filter(function(d) {
          return d.properties.Agency_Bro === type &&
            tenantArray.some(function(entry) {
              return d.properties.Tenant === entry;
            });
        })
    });