Tatiana Frank Tatiana Frank - 7 months ago 28
Javascript Question

Javascript filter returning empty array

I'm using the array.protoype.filter method and it is returning an empty array.

function isSelected(value){

var tagString = $(value).attr('class');
$.each($(brandDrop.selections), function(index, brand) {
if(tagString.indexOf(brand) >= 0) {
console.log(tagString);
return tagString;
}
});

}

var products = [];
$.each($('.products li'), function(index, product){
products.push(product);
});

var brandFiltered = products.filter(isSelected);
console.log(brandFiltered);


Here is the console output for tagstring within the loop and for brandFiltered outside the loop:

AugustaCollection,Crib,publishSK,simmons,simmons-kids,wood
cribs:2058 BellanteCollection,Crib,publishSK,simmons-kids,wood
cribs:2058 BelmontCollection,Crib,publishSK,simmons-kids,wood
cribs:2082 []


This function is triggered by selecting a checkbox. What this filter is meant to do is take an array of html elements, check their class attribute for the presence of a selected value, and return only the class names for the elements which meet the filter's criteria. The console log within the loop is showing the correct elements but for some reason an empty array is returned outside the loop. Am I using the filter method incorrectly?

Answer

Your return tagString; line returns a result to the $.each function, your isSelected function does not currently return anything.

You can edit that function to perform a check and return true when the string is found.

   function isSelected(value){    
      var tagString = $(value).attr('class');
      var foundString = false;
      $.each($(brandDrop.selections), function(index, brand) {
        if(tagString.indexOf(brand) >= 0) {
          console.log(tagString);
          foundString = true;
        }
      });
      return foundString;
    }

Filter functions differently than something like map, it is only used to reduce the size of your array by checking against a condition and returning true or false. If you want to have only an array of classes you can map after the fitler.

brandFiltered = brandFiltered.map(function(x){ return $(x).attr('class'); });
Comments