Leon Gaban
Leon Gaban

Reputation: 39018

How to loop through array and check array values

so I have an Array and I want to loop through the Array and check if the values in it match some strings and if so do something.

This is what I have so far:

var rgt_count = a_related_genres_leon.length; // <- 3 items

for (var i = 0; i < rgt_count; i++) {

    if inArray("Music", a_related_genres_leon) {
        console.log('Music');
    } else if inArray("TV", a_related_genres_leon) {
        console.log('TV');
    } else if inArray("Comedy", a_related_genres_leon) {
        console.log('Comedy');
    }
}

I'm getting a Uncaught SyntaxError: Unexpected token ( error right now.

I also tried this

if text($.inArray("Music", a_related_genres_leon)) {
        console.log('Music');
    } else if text($.inArray("TV", a_related_genres_leon)) {
        console.log('TV');
    } else if text($.inArray("Comedy", a_related_genres_leon)) {
        console.log('Comedy');
    }

Upvotes: 1

Views: 7113

Answers (3)

Adil Shaikh
Adil Shaikh

Reputation: 44740

Refer this for correct syntax and usage

https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Statements/if...else http://api.jquery.com/jQuery.inArray/

if($.inArray("Music", a_related_genres_leon) > -1) {
    console.log('Music');
} else if($.inArray("TV", a_related_genres_leon) > -1) {
    console.log('TV');
} else if($.inArray("Comedy", a_related_genres_leon) > -1) {
    console.log('Comedy');
}

Upvotes: 2

palaѕн
palaѕн

Reputation: 73906

Try this:

if ($.inArray("Music", a_related_genres_leon) > -1) {
    console.log('Music');
} else if ($.inArray("TV", a_related_genres_leon) > -1) {
    console.log('TV');
} else if ($.inArray("Comedy", a_related_genres_leon) > -1) {
    console.log('Comedy');
}

From the jQuery.inArray() API Docs

The $.inArray() method is similar to JavaScript's native .indexOf() method in that it returns -1 when it doesn't find a match. If the first element within the array matches value, $.inArray() returns 0.

Because JavaScript treats 0 as loosely equal to false (i.e. 0 == false, but 0 !== false), if we're checking for the presence of value within array, we need to check if it's not equal to (or greater than) -1.


Upvotes: 1

Felix Kling
Felix Kling

Reputation: 816442

Either search for a particular element in the array:

if ($.inArray("Music", a_related_genres_leon) > -1) {
    console.log('Music');
}
if ($.inArray("TV", a_related_genres_leon) > -1) {
    console.log('TV');
}
if ($.inArray("Comedy", a_related_genres_leon) > -1) {
    console.log('Comedy');
}

or iterate over all elements in the array

var rgt_count = a_related_genres_leon.length; // <- 3 items
for (var i = 0; i < rgt_count; i++) {
    console.log(a_related_genres_leon[i]);
}

but do not do a mixture of both.

Upvotes: 6

Related Questions