Skip to content Skip to sidebar Skip to footer

Javascript :dynamic Expression In Filter Function Based On Variable Values

I am trying to implement a filtering functionality for showing list of buses based on some parameters using lodash.js. Here are four parameters for filtering boardingPoint,droppin

Solution 1:

First of all, finalvar needs to be initialized. It should be initialized to true if you want no filter at all when nothing is selected which I'm assuming that it's the logic you want.

Second, addition assignment '+=' is incorrectly used in this case. Please check here for correct usage.

Third, && is JavaScript operator, it can't be added to another value. That's why you're getting the error.

Here is the revised code which would fix the problems and the expected logic:

// initialize to true means no filter if nothing is selected (return the item).  var finalvar = true;

var tresult = _.filter(result, function(obj) {
    if(bpLocations){
        finalvar = finalvar && _(obj.boardingPoints).map('location').intersection(bpLocations).value().length > 0;
    }
    if(dpLocations){
        finalvar = finalvar && _(obj.droppingPoints).map('location').intersection(dpLocations).value().length > 0;
    }
    if(busTypes){
        finalvar = finalvar && _.includes(busTypes, obj.busType);
    }
    if(operatorNames){
        finalvar = finalvar && _.includes(operatorNames, obj.operatorName);
    }
    return finalvar;
});

Post a Comment for "Javascript :dynamic Expression In Filter Function Based On Variable Values"