Arte
Arte

Reputation: 417

Use "include" for ANY string in a array

I have a search function that takes input/query text from a search bar. I want it to work for multiple search terms like "javascript react" or with more or less search terms. The input is saved in an array in state ("query") and compares to an object "workitem" and its property "description".

Let say:

   workitem.description.includes(this.state.query)

where

  this.state.query // = ["react", "javacript"]

Above will only work for certain situations. I want to see if the array/object includes ANY elements of the state. How to do it?

Upvotes: 1

Views: 70

Answers (2)

Horatiu Jeflea
Horatiu Jeflea

Reputation: 7404

// if needed, do a 
// if (!workitem.description || !this.state.query) {
//     return false;
// }

Considering description is an array:

return workitem.description.some(desc => this.state.query.indexOf(desc) >= 0)

Considering description is a string:

return workitem.description
    .split(' ')
    .some(desc => state.query.indexOf(desc) >= 0);

Upvotes: 2

Clarity
Clarity

Reputation: 10873

How about this:

workitem.description.split(' ').some(str => this.state.query.includes(str)) 

Upvotes: 1

Related Questions