[Vuejs]-Search an array of words or a string with array of words using includes

3đź‘Ť

âś…

So I get your component has an array of “villas”. Each of them has an f property.
There’s also an array this.toFilter which contains a whitelist of words (search terms) and you want to filter the villas whose f property match the search terms.

If f was a string (like a description), a positive match would be when a string includes one of the search terms.

If f was an array (like, the tags of the villa) a positive match would be when there is an non-empty intersection between the tags and the search terms.

Fortunately both strings and arrays have a includes method, so the following should work either way:

villas() {
    return this.$store.state.villas.filter((villa) => {
      return this.toFilter.filter(term=>{
           return villa.f.includes(term);
      }).length>0;
    });
}

2đź‘Ť

I think you use the wrong syntax. If “this.toFilter” is an array and “f” is a string

You should use: this.toFilter.includes(villa.f)

includes

Leave a comment