RedGiant
RedGiant

Reputation: 4748

$.inArray function doesn't return "-1" if item isn't present

Please take a look at this FIDDLE. Why isn't B item returning -1 given that it doesn't have the value "gluten" in the string allergyfree?

Here's the JSON file:

[{"title":"A","allergyfree":"sugar,salt,yeast,wheat,gluten"},{"title":"B","allergyfree":"sugar,salt,starch,yeast,wheat,preservatives"}]

Script:

$.ajax({
    url: "url.json",
    success: function (data) {

        $(data.query.results.json.json).each(function (index, item) { 
         var title = item.title;
         var allergyfree = item.allergyfree;           
         if(allergyfree.length !== 0) {

           allergyfree = allergyfree.split(",");

           $.each(allergyfree,function(i,allergy){

            $('.'+title+allergy).append(jQuery.inArray(allergy, allergyfree));

           });
          }

        });
    },
    error: function () {}
});

I ask this question because I have a problem to check whether the value is present in this thread and someone suggests using inArray function, but it isn't working.

Upvotes: 0

Views: 42

Answers (1)

James Montagne
James Montagne

Reputation: 78630

If you debug (or just have a look at the response) you will find that your ajax request is not returning an entry for B and gluten. So inArray is never called for that combination of title and allergy. That is why the spot for that is left empty.

In fact, your code guarentees that you will never have a case where inArray does not find an entry. You are searching for each element in the array within that same array. So clearly the element will always be found.


What you should be doing instead is looping over a list of all allergies you care about and then checking those in the result of your request. Something like this:

var allergies = ["gluten", "yeast"];

$.ajax({
    /* ... */

    $.each(allergies,function(i,allergy){
        $('.'+title+allergy).append(jQuery.inArray(allergy, allergyfree));
    });

    /* ... */
});

http://jsfiddle.net/cYFLe/119/

Upvotes: 1

Related Questions