Natixco
Natixco

Reputation: 661

Filter doesn't work as the way I idealized in js

I'm trying to filter an array of objects (filteredListing) by an array of numbers (filters['bedroomCount']). I need those items which bedroomCount equals to one of the numbers in the array. The log correctly outputs the booleans, but the if statement is not working. What could be the problem?

   this.filteredListing = this.filteredListing.filter(item => {
      if(this.filters['bedroomCount'].length === 0) {
        return true;
      } else {
        this.filters['bedroomCount'].forEach(elem => {
          console.log(`${item['bedroomCount']}-${elem}  ${item['bedroomCount'] === elem}`)
          if(item['bedroomCount'] === elem) return true;
          else return false;
        });
      }
    });

Upvotes: 1

Views: 58

Answers (1)

Jared Smith
Jared Smith

Reputation: 21926

There's a fairly easy fix here:

this.filteredListing = this.filteredListing.filter(item => {
  if(this.filters['bedroomCount'].length === 0) {
    return true;
  } else {
    return this.filters['bedroomCount'].some(elem => {
      if(item['bedroomCount'] === elem) {
        return true;
      } else {
        return false;
      }
    });
  }
});

But that doesn't fix the thing that caused the error in the first place: the lack of return was hard to spot and hard to test! Let's fix that. Since we're using this I'm assuming we've got a class, so let's add a method encoding the filtering logic:

filterByBedroomCount (item) {
  // It's a lot to type over and over so we'll pull it out.
  const ct = this.filters.bedroomCount;
  // Added bonus, the conditional logic fits readably on to
  // one line now.
  return ct.some(elem => item.bedroomCount === elem);
}

Note that I've also tightened up the conditional logic, you didn't really need the conditional statements when the values themselves are truthy/falsey. It helps that .some on an empty array will always return false meaning you don't even need the length check. Now you can pass in a mock item to the method in a unit test to make sure it does what you want.

Upvotes: 1

Related Questions