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

}
Dr Upvote
  • 8,023
  • 24
  • 91
  • 204
  • Instead of using includes, I'd go with the solution in https://stackoverflow.com/questions/16312528/check-if-an-array-contains-any-element-of-another-array-in-javascript – dskow Dec 14 '17 at 00: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() – charlietfl Dec 14 '17 at 00:30
  • 1
    using reduce `['slug-title-one','slug-title-13'].reduce( (a, b) => a && item.slug.includes(b), true)` – 11thdimension Dec 14 '17 at 00:49

2 Answers2

9

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

}
Gabriele Petrioli
  • 191,379
  • 34
  • 261
  • 317
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;
}
Christian Santos
  • 5,386
  • 1
  • 18
  • 24