1

I have an array 'iid_nn' which will contain ~ 50 values.

If iid_nn contains either 13652 or 39855, then var somevar = 'cabbages' else var somevar = 'carrots'.

If checking for one of those values I could do

if(iid_nn.indexOf(13652) >=0) {
    var somevar = 'cabbages';
} else if(iid_nn.indexOf(39855) >=0) {
    {var somevar = 'cabbages';
} else {
    var somevar = 'carrots';}

But can I do something like

if(iid_nn.indexOf(13652||39855) >=0) {
    var somevar = 'cabbages';
} else {
    var somevar = 'carrots';
}

6 Answers 6

2

You can either modify your indexOf conditional to be:

if (iid_nn.indexOf(13652) > -1 || iid_nn.indexOf(39855) > -1) {

Or you can try using array.some.

if (iid_nn.some(function(i) { return i === 13652 || i === 39855; }) === true) {
Sign up to request clarification or add additional context in comments.

Comments

2

You can’t pass one value to indexOf that will cause it to search for multiple values. You can use the || operator normally, though:

var somevar;

if (iid_nn.indexOf(13652) >= 0 || iid_nn.indexOf(39855) >= 0) {
    somevar = 'cabbages';
} else {
    somevar = 'carrots';
}

And maybe create your own function to do it:

function containsAny(array, items) {
    return array.some(function (item) {
        return items.indexOf(item) !== -1;
    });
}

var somevar;

if (containsAny(iid_nn, [13652, 39855])) {
    somevar = 'cabbages';
} else {
    somevar = 'carrots';
}

Comments

0

To check index of multiple values, you need to update your code to following. Additionally, you can default the value to carrots and then on condition update it.

var somevar = 'carrots';

if(iid_nn.indexOf(13652) >= -1 || iid_nn.indexOf(39855) >= -1) {
    somevar = 'cabbages';
} 

Comments

0

Your condition is kind of wrong.

if(iid_nn.indexOf(39855)!=-1 || iid_nn.indexOf(13652)!=-1) 
{
    var somevar = 'cabbages';
} else {
    var somevar = 'carrots';
}

Comments

0

Try this:

if((iid_nn.indexOf(13652) !=-1)||(iid_nn.indexOf(39855) !=-1)) {
    var somevar = 'cabbages';
} else {
    var somevar = 'carrots';
}

Comments

0
var iid_nn = [13652],
    somevar;
if (~iid_nn.indexOf(13652) || ~iid_nn.indexOf(39855)) {
    somevar = 'cabbages';
} else {
    somevar = 'carrots';
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.