Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

check for multiple Array.includes using or [duplicate]

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

}
like image 972
fred randall Avatar asked Nov 08 '25 09:11

fred randall


2 Answers

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

}
like image 77
Gabriele Petrioli Avatar answered Nov 09 '25 23:11

Gabriele Petrioli


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;
}
like image 23
Christian Santos Avatar answered Nov 09 '25 21:11

Christian Santos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!