Search code examples
javascriptvue.jsfilterinclude

Search an array of words or a string with array of words using includes


I have a string or I can make it an array of strings. and when I try to filter it using includes if there are more than one search terms it doesn't return anything where is my mistake?

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

here is toFilter is the array of search terms and f is the string i make the searching


Solution

  • 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;
        });
    }