How to create custom search function in VueJS?

Viewed 55

I want to create custom search function in VueJS.

For example, I have 2 products PlayStation Plus 90 Days IE and PlayStation Plus 90 Days NO. For now, to find something I have to input the full name, but I want to input just PlayStation 90 and get in my search field the both products. How can I do that?

I was trying to do something like that, but it doesn't work:

computed: {
customSearch() {
  return this.result.filter(product => {
    return product.text
      .toLowerCase()
      .includes(this.searchInput.toLowerCase())
  })
}

},

Also, I was thinking about to split sting like that ["PlayStation", "Plus", "90", "Days", "IE"] and find by key words, but I don't know how to make it :\

Thanks for answers!

1 Answers

Using Array#every:

const 
  data = [{ text:"PlayStation Plus 90 Days IE" }, { text:"PlayStation Plus 90 Days NO" }],
  searchInput = "PlayStation 90";

const searchWords = searchInput
  .toLowerCase() // convert to lower-case
  .split(/\s+/); // split to words
const result = data.filter(({ text }) => 
  searchWords.every(str => // every word should be in the text of the current product
    text.toLowerCase().includes(str)
  )
);
  
console.log(result);

Related