[Vuejs]-Multiple condition filter

1👍

What about:

booksFilter() {
  return this.books.filter(x => {
    if (this.filters.options.length> 0) {
      boolean condition = true; 
      if (this.filters.options.indexOf(0)!=-1) {
         conditon = conditon && x.price>1000
      }

      if (this.filters.options.indexOf(1)!=-1) {
         conditon = conditon && x.name == "Book1";
      }

      return condition;
    else {
      return true;
    }  
  })
}

Hope it will resolve your case.

0👍

It seems as your filter is incorrect.

For simplicity purposes i divided into 2 sequential filters, one for each checkbox:

computed:{
    booksFilter(){
      return this.books.filter(x => {
        if(this.filters.options.length && this.filters.options.indexOf(0)!=-1){
          return x.price>1000;
        }
        else{
          return true;
        }  
      }).filter(x => {
        if(this.filters.options.length && this.filters.options.indexOf(1)!=-1){
          return x.name == "Book1";
        }
        else{
          return true;
        }  
      })
    }
  }  

0👍

Update your logic like that to achieve the result:

return (this.filters.options.indexOf(0) === -1 || x.price > 1000)
  && (this.filters.options.indexOf(1) === -1 || x.name === "Book1");

this.filters.options.indexOf(0) === -1 || x.price > 1000 – filter 0 is not selected, return true OR filter by price
AND
this.filters.options.indexOf(1) === -1 || x.name === "Book1" – filter 1 is not selected, return true OR filter by name

👤NaN

Leave a comment