0

I need to filter array with compare string and numeric result values. But get filter array values, while I enter both values. Otherwise I can't get values. That means if enter only string value I can't get filter array values.

var fullArray = [{stringValue:"apple", numericValue:"40"}, {stringValue:"banana", numericValue:"20"}, {stringValue:"berry", numericValue:"30"}, {stringValue:"mango", numericValue:"10"}]

    _.filter(fullArray, function(el){
        if(el.stringValue.toLowerCase().indexOf(stringResultValue.toLowerCase())>=0 && el.numericValue==numericResultValue){
            resultFilter.push(el);
        }
    });
6
  • what is resultFilter, stringResultValue, numericResultValue? Take an example of input data and expected result please Commented Feb 28, 2017 at 11:45
  • See Array.prototype.filter. Lodash's filter should work similar. Commented Feb 28, 2017 at 11:59
  • @AndrewParamoshkin, resultFilter is get a final result array. stringResultValue and numericResultValue both are already get value from click function. Commented Feb 28, 2017 at 12:25
  • @barbsan, yeah there is example is only filter string or numeric. I need filter with both values. Commented Feb 28, 2017 at 12:26
  • 1
    @barbsan, yeah thanks dude! Commented Feb 28, 2017 at 12:44

1 Answer 1

1

filter expects a function that returns something truthy for elements that should be in the new array, and something falsey if they shouldn't. You should have something like:

var fullArray = [{stringValue:"apple", numericValue:"40"}, {stringValue:"banana", numericValue:"20"}, {stringValue:"berry", numericValue:"30"}, {stringValue:"mango", numericValue:"10"}]

resultFilter = _.filter(fullArray, function(el){
    return el.stringValue.toLowerCase().indexOf(stringResultValue.toLowerCase()) >= 0 && 
           el.numericValue === numericResultValue;
});

A shorter version, using ES6 syntax:

resultFilter = fullArray.filter(el => 
    el.stringValue.toLowerCase().includes(stringResultValue.toLowerCase()) && 
    el.numericValue === numericResultValue;
);
Sign up to request clarification or add additional context in comments.

Comments