Reputation: 69
For example:
I have a array
const tags = ['size-1', 'size-2', 'discount-xyz']
In this case to check if I have a substring with discount in it, I have converted the array to a string
const arrayToString = tags.toString();
The output:
const tagsArrayToString = size-1,size-2,discount-wyx;
And I check if with a IF statement like this:
if ( tagsArrayToString.indexOf("discount") !== -1 ) { doSomething }
So far so good. But how can I get the full String like "discount-xyz"?
Upvotes: 1
Views: 545
Reputation: 3797
Find the index of the discount tag using findIndex method, in turn find the tag itself via the index of the array.
const index = tags.findIndex(t => t.indexOf('discount') !== -1);
const discountTag = tags[index];
Upvotes: 1
Reputation: 312136
I wouldn't convert the tags
array to a string - you already have the strings nice and separated, and this would only make things harder.
Instead, you could filter
the array:
const filteredTags = tags.filter(t => t.includes('discount'));
Or, if you know there's just one such string, you could use find
to get it:
const relevantTag = tags.find(t => t.includes('discount'));
Upvotes: 2