user12009061
user12009061

Reputation:

How to check if the following value contains one of the strings in the array in javascript?

I have an array

let items = ['hat', 'shirt', 'glasses', 'jeans']

this.mainItem is a property that has a value for sample 'black-hat'

How can I check if this.mainItem contains one of the strings in the array and if there is a mtach return that array item otherwise return '' empty string?

Upvotes: 0

Views: 117

Answers (3)

K. Drab
K. Drab

Reputation: 193

You can use the find method:

items.find((item) => this.mainItem.includes(item)) || ""

Upvotes: 1

user14520680
user14520680

Reputation:

You can use the boolean:

items.findIndex((el) => this.mainItem.includes(el)) !== -1

We use the new findIndex method and check if main tiem includes the element. If not, then the function returns -1

Upvotes: 0

Ahmad MOUSSA
Ahmad MOUSSA

Reputation: 2906

You can use the .filter() function:

items.filter((item) => this.mainItem.includes(item))// will return Array [ "hat" ]

Upvotes: 0

Related Questions