4

How do I test for multiple .includes with Array.includes() in my if statement? The below seems to work on one item, ie. slug-title-one but ignores the second.

if (item.slug.includes('slug-title-one' || 'slug-title-13')) {
     // checks for and displays if either

}
3
  • Instead of using includes, I'd go with the solution in stackoverflow.com/questions/16312528/… Commented Dec 14, 2017 at 0:17
  • Because || evaluates the first string as truthy and so that is what is passed to includes(). You have to check both separately. Read the documentation for includes() Commented Dec 14, 2017 at 0:30
  • 1
    using reduce ['slug-title-one','slug-title-13'].reduce( (a, b) => a && item.slug.includes(b), true) Commented Dec 14, 2017 at 0:49

2 Answers 2

10

As the documentation the Array.includes can only test for a single element.

You could reverse your logic though and use

if (['slug-title-one','slug-title-13'].some(slug => item.slug.includes(slug))) {
     // checks for and displays if either

}
Sign up to request clarification or add additional context in comments.

4 Comments

Hey, thanks but still on occasion this responds with 'Uncaught TypeError: Cannot read property 'includes' of null'
@Billy that means that the item.slug is null.
The problem is sometimes it will be null, but other times not, I don't want the page to break on the rare instances it is null
wrap the whole if in another one the does if (item.slug) {...} . Btw this problem would exist in your original attempt as well.
1

You have a few options. Here are some ideas:

Repeat includes

if (item.slug.includes('slug-title-one') || item.slug.includes('slug-title-13')) { ... }

Helper function

if( includes(item.slug, 'slug-title-one', 'slug-title-13') ) { ... }

function includes() {

    var args = Array.prototype.slice.call(arguments);
    var target = args[0];
    var strs = args.slice(1); // remove first element

    for(var i = 0; i < strs.length; i++) {
        if(target.includes(strs[i])) {
            return true;
        }
    }

    return false;
}

1 Comment

The OP talks about Array.includes which means the item.slug is an array. So the regex version wouldn't work.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.