Reputation:
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
Reputation: 193
You can use the find
method:
items.find((item) => this.mainItem.includes(item)) || ""
Upvotes: 1
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
Reputation: 2906
You can use the .filter()
function:
items.filter((item) => this.mainItem.includes(item))// will return Array [ "hat" ]
Upvotes: 0